我想编写一个正则表达式来从输入行中获取名称和城市。
示例:
嗨大卫!你好吗?你现在在钦奈吗?
我需要从这篇文章中获取 david 和 chennai
我编写了下面的代码,它工作正常,但每当该行中有换行符时,它就无法工作
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
whitespace 速记字符类,并且意味着您*不能在模式中过多依赖 \Q...\E
。
我建议更改正则表达式:
String regex1="Hi\\s+(.*?)\\s+how\\s+are\\s+you\\?\\s+are\\s+you\\s+in\\s+(.*?)\\s+now\\?";
请参阅regex demo
输出:
Passage : David! is fine and yes I am in chennai
Ram! is fine and yes I am in chennai
关于java - pattern.dotall 在\Q 和\E 之间不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35406299/