Java pattern.dotall在\Q和\E之间不起作用
我想编写一个正则表达式,从输入行获取name和city 例如: 嗨,大卫!你好吗?你现在在钦奈吗 我要把大卫和钦奈从这段路上接过来 我写了下面的代码,它工作得很好,但当这行中有换行符时,它就不工作了Java pattern.dotall在\Q和\E之间不起作用,java,regex,Java,Regex,我想编写一个正则表达式,从输入行获取name和city 例如: 嗨,大卫!你好吗?你现在在钦奈吗 我要把大卫和钦奈从这段路上接过来 我写了下面的代码,它工作得很好,但当这行中有换行符时,它就不工作了 package com.test; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Testing { public static void main(String[] args)
package com.test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Testing {
public static void main(String[] args) {
String input = "Passage : Hi David! how are you? are you in chennai now? "
+ "\n Hi Ram! how are you?\n are you in chennai now?";
String regex1="\\QHi \\E(.*?)\\Q! how are you? are you in \\E(.*?)\\Q now?\\E";
Pattern p = Pattern.compile(regex1,Pattern.DOTALL);
Matcher m = p.matcher(input);
StringBuffer result = new StringBuffer();
while (m.find()) {
m.appendReplacement(result,m.group(1)+" is fine and yes I am in "+m.group(2));
}
m.appendTail(result);
System.out.println(result);
}
}
输出:
大卫很好,是的,我在钦奈
嗨,拉姆!你好吗?
你现在在钦奈吗
预期产量
大卫很好,是的,我在钦奈。拉姆很好,是的,我在钦奈
注意:我也使用了Pattern.DOTALL
提前感谢 如果您的输入可以包含双空格,或者换行符/回车符而不是常规空格,那么您应该使用
\s
空白速记字符类,这也意味着您*不能在模式中依赖\Q..\E
我建议将正则表达式更改为:
String regex1="Hi\\s+(.*?)\\s+how\\s+are\\s+you\\?\\s+are\\s+you\\s+in\\s+(.*?)\\s+now\\?";
见
输出:
Passage : David! is fine and yes I am in chennai
Ram! is fine and yes I am in chennai
我想问题是这行分隔符
你?\n是,你的模式\\Q!你好吗?您是否在\\E
中并不能解释它。这确实是导致正则表达式失败的原因。使用\\s+
而不是空格,您不能依赖这里的\Q…\E
。使用String regex1=“Hi\\s+(.*)\\s+how\\s+are\\s+you\\?\\s+are\\s+you\\s+in\\s+(.*)\\s+now\\?”
如果要保留当前正则表达式,可以执行以下操作:p.matcher(input.replaceAll(“\n”,”)
这将删除行分隔符。因此,Pattern.DOTALL
与\Q..之间的内容无关。\E
。它只影响可以匹配换行符的
模式。模式中的文字空格不能与换行符匹配。我希望这是清楚的。