2014-11-14 62 views
0

说我编译正则表达式模式:Java的模式匹配行为

String myString = "manifest"; 
p = Pattern.compile(myPattern, Pattern.CASE_INSENSITIVE ); 
Matcher m = p.matcher(myString); 
if (m.matches()){ 
    ..... 
} 

当我指定myPattern作为ni例如,myString没有得到匹配。但是,当我指定myPattern.*ni.*时,它会得到匹配。

在我的代码的后面部分,我将要用新模式替换myPattern中定义的任何内容。例如,如果我指定ni作为要替换的2个字符,则它将只替换ni。如果我指定.*ni.*,那么整个字符串将被替换为新的模式。现在我的问题是它不匹配。

有什么可以解决这个问题? 感谢

+0

照片直接使用.replace? – vks

+0

*你好吗*'m'? –

回答

3

这一切都取决于它Matcher方法使用:

  • 匹配():当且仅当整个区域的序列匹配此匹配器模式
  • find()方法:如果为true且仅当,输入序列的子序列相匹配此匹配器模式

实施例:

String input = "manifest"; 
Matcher m1 = Pattern.compile("ni").matcher(input); 
System.out.println(m1.matches()); // false 
System.out.println(m1.find()); // true 
Matcher m2 = Pattern.compile(".*ni.*").matcher(input); 
System.out.println(m2.matches()); // true 
System.out.println(m2.find()); // false 

此外,发现(),您可以遍历匹配:

while (m2.find()) { 
    String groupX = m2.group(x); 
} 
4

matches尝试匹配针对图案的整个输入(因为它在文档中表示),当然manifest不是ni精确匹配,但是对于.*ni.*精确匹配。但是,例如,如果您使用find,它将在的输入内搜索某处的模式。还有lookingAt,它会尝试匹配输入内“当前”位置的模式。

+0

嗨,谢谢,我用'火柴'。所以我应该使用'find' ...我会试试看。谢谢 – dorothy