1

I want to concatenate a regex and a string and want to compare the resultant string with another string.How can I do that in java?

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegexMatching {


public static void main(String aaa[])
{
    String testStr="anjaneyPANDEY";

    String regEx = "([A-Z])";

    Pattern pattern = Pattern.compile(regEx);
    Matcher matcher = pattern.matcher(testStr);

    String st="anjaney"+regEx;
    if(testStr.matches(st))
        System.out.println("YES");
    else System.out.println("NO");
}
}
1
  • add a + or a * at the end of your regex, depending on what you want. have you read about greedy and non-greedy regex patterns yet? Commented Jun 3, 2014 at 12:50

2 Answers 2

5

It seems that you forgot to add + in your regex to let it match one or more uppercase character. You should use [A-Z]+ since matches checks if entire string can be matched with regex.

Also you should use created Matcher instance instead of testStr.matches(st) to not recompile every time your pattern. So your code can look like

String regEx = "([A-Z]+)";
String st = "anjaney" + regEx;

Pattern pattern = Pattern.compile(st);
Matcher matcher = pattern.matcher(testStr);

if (matcher.matches())
    System.out.println("YES");
else
    System.out.println("NO");

This approach is OK if you know that string you want to combine with regex doesn't have any regex metacharacters like ( * + and so on.
But if you are not sure about it then you need to create escape such metacharacters. In that case you can use Pattern.quote() method. So instead of

String st = "anjaney" + regEx;

you can use

String st = Pattern.quote("anjaney") + regEx;
Sign up to request clarification or add additional context in comments.

Comments

0

try it:

    String testStr = "anjaneyPANDEY";

    String regEx = "([A-Z])+";

    String st = "anjaney" + regEx;


    if (testStr.matches(st)) {
        System.out.println("YES");
    } else {
        System.out.println("NO");
    }

Comments

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.