简体   繁体   中英

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.

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()

if (matcher1.find()) 

instead of String#matches() that matches for whole string not just part of it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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