Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial matching of Regular expression [duplicate]

Tags:

java

regex

I have a String that is incrementally built. While the string being built, it is matched as a whole by a regular expression and when a match is found, a certain task is performed.

My requirement is: If in the middle of the string building process it is found that there is no way an exact match will be found, then the string should be reset and the build process should be re-initiated.

For example if a regular expression is "mada12gaskar" and when a char "3" is added to an existing string "mada1" the string should be cleared and the build process should start over again as "mada13" will never match with "mada12gaskar". Is this possible through Java regex API?

like image 330
jrpalla Avatar asked Dec 05 '25 19:12

jrpalla


1 Answers

I think I found a possible solution to your problem.

Look at Matcher#hitEnd() method:

Returns true if the end of input was hit by the search engine in the last match operation performed by this matcher.

When this method returns true, then it is possible that more input would have changed the result of the last search.

Now, simply match the regexp against your not-yet-fully-constructed String using a Matcher (obtainable via a Pattern instance) and look at the results:

  • if it matched, you have your winner
  • if it didn't match, look at hitEnd():
    • if it's true, build more String and try again
    • if it's false, the current String could never be matched, you can drop it and start over
like image 91
Petr Janeček Avatar answered Dec 08 '25 07:12

Petr Janeček



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!