简体   繁体   中英

Java Regular Expressions find matches within x characters

I've been pulling my hair out over this, and I know it's a simple solution that just seems to escape me at the moment.

I am attempting to perform a match using a Regex code (client side, character classes only) that will match "looking for" within 20 spaces (any character) of "male". I don't care what the characters or spaces are, it must not find a match if the two words/phrases are more than 20 characters apart.

I have the code setup to match the phrases I just need to know how to set the parameter of a distance search. "Only match Looking for with Male if they are within zero to twenty characters of each other.

(?i).*looking for.{0,20}male.*

The (?i) flag is just "ignore case".

EDIT : with the suggestions:

Pattern.compile("(?is).*\\blooking for\\b.{0,20}\\bman\\b.*");

Maybe you shouldn't pull your hair out but instead start with the root of the issue? I mean can't you write your code/application more logical so you wouldn't need to do such weird string search with even weirder distance matching?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM