Reputation: 2465
I'm doing a project which requires numerical pattern matching.
For example i want to know whether Value = 1331
is a part of 680+651 = 1331
or not, i.e. i want to match 1331
with 680+651 = 1331
or any other given string.
I'm trying pattern matching in java for the first time and i could not succeed. Below is my code snippet.
String REGEX1=s1; //s1 is '1331'
pattern = Pattern.compile(REGEX1);
matcher = pattern.matcher(line_out); //line_out is for ex. 680+651 = 1331
System.out.println("lookingAt(): "+matcher.lookingAt());
System.out.println("matches(): "+matcher.matches());
It is returning false all the times. Pls help me.
Upvotes: 3
Views: 195
Reputation: 45578
matches()
is the wrong method for this, use find()
.
http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Matcher.html says:
public boolean matches()
Attempts to match the entire input sequence against the pattern.
and
public boolean find()
Attempts to find the next subsequence of the input sequence that matches the pattern.
Upvotes: 2
Reputation: 32969
The matches
method requires a perfect, full exact match. Since there is more text in 680+651=1331
than what is matched by the regex 1331
, matches returns false
.
As I pointed out in Brian's post, you need to be careful in your regex to ensure that a regex of 1331
does not match the number 213312
unless that is what you want.
Upvotes: 2
Reputation: 76918
matches()
requires that the pattern be a complete match, not a partial.
You either need to change your pattern to something like .*= 1331$
or use the find()
method which will do a partial match.
Upvotes: 3