Wednesday, May 18, 2022

[FIXED] How to write a regex that prevents partial matching

Issue

How do I build a regex pattern that searches over a text T and tries to find a search string S.

There are 2 requirements:

  1. S could be made of any character.
  2. S could be anywhere in the string but can't be part of a word.

I know that in order to escape special regex characters I put the search string between \Q and \E as such:

\EMySearch_String\Q

How do I prevent finding partial matching of S in T?


Solution

You can do like this if
can't be part of a word
is interpreted as
preceded by start-of-string or space and followed by end-of-string or space:

String s = "3894$75\\/^()";
String text = "fdsfsd3894$75\\/^()dasdasd 22348 3894$75\\/^()";
Matcher m = Pattern.compile("(?<=^|\\s)\\Q" + s + "\\E(?=\\s|$)").matcher(text);
while (m.find()) {
    System.out.println("Found match! :'" + m.group() + "'");
}

This prints only one

Found match! :'3894$75/^()'



Answered By - Keppil
Answer Checked By - Mildred Charles (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.