我想编写一个正则表达式,从输入行中获取名称和城市。
例子:
嗨大卫!你好吗?你现在在钦奈吗?
我要把大卫和陈奈从这一段里拿来
我编写了下面的代码,它运行得很好,但是只要这一行有断行,它就不能工作。
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。
提前谢谢!
发布于 2016-02-15 10:45:20
如果输入可以包含双空格,或者行提要/回车返回,而不是常规空格,则应该使用\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 chennaihttps://stackoverflow.com/questions/35406299
复制相似问题