Java String Class匹配Method

时间:2015-03-04 09:42:00

标签: java regex string

我的计划

public class EHFix {
static String regExpCharacter = "(.*)HI(.*)";
public static void main(String[] args) {

    String val="HI  How  are you";
    String secondValue="HI  How \r are you";
    String thirdValue="HI  How \n are you";         
    System.out.println(val.matches(regExpCharacter));
    System.out.println(secondValue.matches(regExpCharacter));
    System.out.println(thirdValue.matches(regExpCharacter));

}

My output is: true 
              false
              false

为什么对于secondValue和thirdValue变量,即使它与regExpCharacter匹配,它也会输出false?

1 个答案:

答案 0 :(得分:0)

因为.默认情况下不会与换行符\n\r匹配。所以改变你的正则表达式,

"(?s)(.*)HI(.*)"

(?s) DOTALL修饰符,它使正则表达式中的点也与换行符匹配。

"([\\s\\S]*?)HI([\\s\\S]*)"

[\s\S]匹配任何空格或非空格字符。 \s也会对换行符进行匹配。

String regExpCharacter = "(?s)(.*)HI(.*)";
String val="HI  How  are you";
String secondValue="HI  How \r are you";
String thirdValue="HI  How \n are you";         
System.out.println(val.matches(regExpCharacter));
System.out.println(secondValue.matches(regExpCharacter));
System.out.println(thirdValue.matches(regExpCharacter));

<强>输出:

true
true
true