Newmanater
Newmanater

Reputation: 153

Valid Regex statement is not a valid match in Java

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?

Upvotes: 2

Views: 608

Answers (3)

patty
patty

Reputation: 58

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

Upvotes: 1

ddavison
ddavison

Reputation: 29042

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 }

Upvotes: 2

npinti
npinti

Reputation: 52185

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()) {
    ...
}

Upvotes: 2

Related Questions