-2

I need to build a regular expression that will return true or false is the specified word is in the same sentence with either word "County" or "Counties" and comes either before or after either of those words and is no more than either 10 words or 100 characters apart with "County" or "Counties".

For example :

County test test1 test2 Word test3 test4

or

Test test1 test2 test3 Word test4 test5 Counties test6 test7

should return true, while

Counties test1 test2 test3 test4 test5 test6 test7 test8 test9 test test8 test3 test4 Word test5 test7

Should return false

Here is what I got:

\bWord\W+(?:\w+\W+){0,10}?Counties\b

I added County but it only works so far if words County and/or Counties are after Word:

\bWord\W+(?:\w+\W+){0,10}?(Counties|County)\b

Can anyone please point me in the right direction?

3
  • What have you tried? It's very difficult to help you with your code if you don't include the code you need help with. Also, you might want to review SO's How to ask a good question page.
    – ghoti
    Apr 22, 2015 at 19:29
  • What language? This is probably best handled in two steps.
    – dawg
    Apr 22, 2015 at 19:46
  • I am just trying to get it to wrok here regex101.com Apr 22, 2015 at 20:30

1 Answer 1

1

Does this solve your problem? Tried on regex101

Word\s\W*(?:(?!Word)\w+\W*){0,10}?(?:Counties|County)|(?:Counties|County)\s\W*(?:\w+\W*){0,10}?Word
2
  • This is working most of the time. But what about if I have something like this "testing string testing again Counties (Test2, Test, Word)"? I tried and it didn't work. Was the parenthesis a problem? Apr 23, 2015 at 15:19
  • Yes, the parentheses (as well as the commas) are probably what is causing it not to work. You might try replacing occurrences of \s (one space) above with \W+ (one or more non-word characters). Apr 23, 2015 at 16:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.