2

I'm trying to create a very simple regex statement to tell me if a String contains a match.

The Regex statement:

%.+%

The String I'm scanning:

"Property:%substitute.candidate%_substitute.candidate%End"

I've used an the online the tools to validate my work and using the supplied Regex and the given String that it is a match. however when I run it in my Java program it does not return as a match.

In my Java Code I'm using the following to match the string.

if(replacedString.matches(regex)){}

Can anyone explain the reason why it is not working?

1
  • 1
    you should adjust your regexp too, because it uses a hungry approach, therefore try %[^%]+% instead of %.+% Mar 12, 2015 at 15:34

3 Answers 3

2

matches() expects the ENTIRE string to be matched.

What you want, is a Pattern and Matcher.

Pattern p = Pattern.compile("%.+%");
Matcher m = p.matcher("Property:%substitute.candidate%_substitute.candidate%End");
if (m.find()) { // found it }
1
  • Thank you very much, this was spot on.
    – Newmanater
    Mar 13, 2015 at 8:11
2

The problem is that when you use matches(), the engine will add the ^ and $ anchors so that your string must match exactly.

In your case, the matches is expecting that the string starts and ends with %, which is not the case.

To go around this, use find().

EDIT: As per @Pshemo's comment, you would need to do this:

Pattern pattern = Pattern.compile("%.+%");
String str = "...";
Matcher matcher = pattern.matcher(str);
if(matcher.find()) {
    ...
}
2
  • String doesn't have find method which may be confusing for OP.
    – Pshemo
    Mar 12, 2015 at 15:22
  • @Pshemo: I see what you mean, I though he was already using the Pattern class. Amended my answer as per your recommendation.
    – npinti
    Mar 12, 2015 at 15:25
1

String#matches() takes a regex as parameter and ^ and $ are the implicit anchors. So, the matches method matches the entire string. You can choose to either try matching the whole string like this : mystring.matches(".your_regex."); or try using a pattern/matcher in combination with find/replace as mentioned in previous answer

1
  • Correct. Now instead of posting it as comment (which not everyone reads) edit your post and place this explanation there.
    – Pshemo
    Mar 12, 2015 at 15:45

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.