我想在另一个字符串中搜索字符串(由字符串和正则表达式连接形成)。如果第一个字符串出现在第二个字符串中,那么我想获得匹配短语的起始和结束地址。 对于以下代码,我想在“baby_NN accessories_NNS India_NNP is_VBZ an_DT online_JJ shopping_NN portal_NN”中搜索“baby accessories India”,并希望获得“baby_NN accessories_NNS India_NNP”作为结果。
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatching {
public static void main(String aaa[])throws IOException
{
String line="baby accessories India";
String []str=line.split("\\ ");
String temp="";
int i,j;
j=0;
String regEx1 = "([A-Z]+)[$]?";
for(i=0;i<str.length;i++)
temp=temp+str[i]+"_"+regEx1+" ";
String para2="baby_NN accessories_NNS India_NNP is_VBZ an_DT online_JJ shopping_NN portal_NN ";
Pattern pattern1 = Pattern.compile(temp);
Matcher matcher1 = pattern1.matcher(para2);
if (para2.matches(temp)) {
i = matcher1.start();
j = matcher1.end();
String temp1=para2.substring(i,j);
System.out.println(temp1);
}
else {
System.out.println("Error");
}
}
}
答案 0 :(得分:3)
尝试使用Matcher#find()
if (matcher1.find())
而不是匹配整个字符串的String#matches()而不仅仅是其中的一部分。
if (para2.matches(temp))
输出:
baby_NN accessories_NNS India_NNP
再做一次改动
if (matcher1.find()) {
i = matcher1.start();
j = matcher1.end();
String temp1 = para2.substring(i, j-1); // Use (j-1) to skip last space character
System.out.println(temp1);
}