0

I have the following regex:

^\s*((\b[^0-9]+\b)\s*){2}$

This regex expects the string to have two words with no number. Thus, for instance, /^\s*((\b[^0-9]+\b)\s*){2}$/g.test('Word Otherword') returns true, as expected, and /^\s*((\b[^0-9]+\b)\s*){2}$/g.test('OnlyOneWord') returns false, as it contains only one word.

The problem is that Regex is treating accentuated characters like ã or é as words boundaries (\b). This way, if I test /^\s*((\b[^0-9]+\b)\s*){2}$/g.test('João') it returns `true', as it were two words instead of only one.

How could I solve this problem?

Mateus Felipe
  • 906
  • 1
  • 12
  • 36
  • BTW, if you plan to match a string consisting of two chunks of non-digit chars, just use `/^[^0-9]+\s+[^0-9]+$/`. Note `[^0-9]` matches spaces, too. – Wiktor Stribiżew May 03 '18 at 17:22
  • It seems to be, but simply replacing `\b` with `(?:^|\\s)` doesn't work at all. With `/^\s*(((?:^|\\s)[^0-9]+(?:^|\\s))\s*){2}$/g.test("João Ferreira")` we have `false` instead of `true`. – Mateus Felipe May 03 '18 at 17:23
  • Do not try to fix your regex, it is a mess. You need to completely redesign it according to some rules (you have not provided any pattern requirements in the question). – Wiktor Stribiżew May 03 '18 at 17:24
  • Well, I don't want to match only two characters. I want to match *at least* two. This one in my question is just a reproducible example. But in practice I would run `^\s*((\b[^0-9]+\b)\s*){2,}$`, so it matches 2 or more. – Mateus Felipe May 03 '18 at 17:26
  • 1
    To match 2 or more whitespace-separated non-digit chunks you may use `/^\s*[^0-9\s]+(?:\s+[^\s0-9]+)+\s*$/` – Wiktor Stribiżew May 03 '18 at 17:27
  • Well, it seems to work. So, can I say {x,y} is useless? – Mateus Felipe May 03 '18 at 17:29
  • 1
    No, `{x,y}` is very useful. However, you should not try to shorten the pattern to sacrifice precision of matching. – Wiktor Stribiżew May 03 '18 at 17:32
  • 1
    Well given that this was marked as duplicate I'll give you the regex here `/^\D*[A-zÀ-ÿ ]\D+\s\D+/g` I've had good luck with that. Happy Coding – Cory Kleiser May 03 '18 at 17:49

0 Answers0