简体   繁体   English

Java字符串和正则表达式匹配

[英]Java string and regex matching

I want to search a string(formed by concatenation of string and a regex) in another string.If the 1st string is present in the second string then i want to get the starting and ending addresses of matched phrase. 我想在另一个字符串中搜索字符串(由字符串和正则表达式连接形成)。如果第一个字符串出现在第二个字符串中,那么我想获得匹配短语的起始和结束地址。 For in the following code I want to search "baby accessories India" in "baby_NN accessories_NNS India_NNP is_VBZ an_DT online_JJ shopping_NN portal_NN " and want to get "baby_NN accessories_NNS India_NNP" as result. 对于以下代码,我想在“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");
        }

}
}

Try with Matcher#find() 试试Matcher#find()

if (matcher1.find()) 

instead of String#matches() that matches for whole string not just part of it. 而不是String#matches()匹配整个字符串而不仅仅是它的一部分。

if (para2.matches(temp))

output: 输出:

baby_NN accessories_NNS India_NNP  

One more changes 还有一个变化

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);
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM