例如,我有一组字符串:
"Abc zcf",
"Abcd zcf",
"Zcf Abc",
"Zcf Abcd",
"Test ez",
"Rabc Jabc"如何在这个集合中找到任何以"abc“字符开头的单词?在我的示例中,它将是字符串
"Abc zcf",
"Zcf Abc",
"Abcd zcf",
"Zcf Abcd"发布于 2013-06-14 20:06:50
您需要匹配任何内容,后跟单词边界,然后是abc。您还希望以不区分大小写的方式完成此操作。模式
(?i).*\\babc.*都会起作用的。一个简单的例子
public static void main(String[] args) throws Exception {
final Pattern pattern = Pattern.compile("(?i).*\\babc.*");
final String[] in = {
"Abc zcf",
"Abcd zcf",
"Zcf Abc",
"Zcf Abcd",
"Test ez",
"Rabc Jabc"};
for (final String s : in) {
final Matcher m = pattern.matcher(s);
if (m.matches()) {
System.out.println(s);
}
}
}输出:
Abc zcf
Abcd zcf
Zcf Abc
Zcf Abcd编辑
根据@fge关于匹配整个模式的评论,这里提供了一种在String中搜索模式的更简洁的方法。
public static void main(String[] args) throws Exception {
final Pattern pattern = Pattern.compile("(?i)(?<=\\b)abc");
final String[] in = {
"Abc zcf",
"Abcd zcf",
"Zcf Abc",
"Zcf Abcd",
"Test ez",
"Rabc Jabc"};
for (final String s : in) {
final Matcher m = pattern.matcher(s);
if (m.find()) {
System.out.println(s);
}
}
}这将显示find abc,它的前面是\b -即单词abc。输出是相同的。
发布于 2013-06-14 20:01:01
您必须使用Pattern
final Pattern p = Pattern.compile("\\bAbc");
// ...
if (p.matcher(input).find())
// match仅供参考,\b是单词锚。Java对单词字符的定义是下划线、数字或字母。
发布于 2013-06-14 20:03:08
您可以使用:
if( maChaine.startWith("Abc") )
{
list.add( maChaine ) ;
}https://stackoverflow.com/questions/17107941
复制相似问题