我的计划
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?
答案 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