4

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

}
}
2
  • So, what have you tried? What is the outcome of your code? Is it Error or is it something else? The code you posted won't even compile. Commented Jun 4, 2014 at 6:48
  • @Stephan:There was a minor error i had used matcher instead of matcher1..Now it is correct..:)..The output is Error Commented Jun 4, 2014 at 6:55

1 Answer 1

3

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);
} 
Sign up to request clarification or add additional context in comments.

2 Comments

And also use Pattern.quote() to escape any special characters in the input string.
Yes you are right all the characters that are already part of regex pattern must be escaped if trying to match these special characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.