PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, May 18, 2022

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

 May 18, 2022     java, partial, regex, search     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing