1

I devised the regular expression (see fiddle) /(\+|0|\()[\d()\s-]{6,20}\d/g to match phone numbers in the formats below.

(\+|0|\() is to match + or 0 or ( in the first place

[\d()\s-] is to match digits, brackets, spaces, hyphens in between

\d is to match a digit in the last place

+43 543 765 5434

0043 543 765 5434

0543 765 5434

+43 (0)543 765 5434

05437655434

0543-765-5434

Unfortunately this regex also matches numbers with linebreaks in between, like

"+43

654 416 4444" or

"stowasser09

65

808090"

  1. I therefore thought of replacing \s in the regex with [^\S\r\n] to match whitespaces but not linebreaks but couldn't get it to work?

  2. Also it would be nice to apply{6,20} to the whole regex, not just the [\d()\s-]-part please? I imagine something like /((\+|0|\()[\d()\s-]\d){6,20}/g, i.e. the whole matched phone number should not be shorter than 6 and not longer than 20 characters, including the + | 0 | ( in the first place and the last digit.

Thank you!

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Pingui
  • 1,312
  • 4
  • 15
  • 28
  • 2
    Just replace `\s` with space char (`' '`) – hindmost Aug 17 '14 at 20:25
  • hindmost suggestion will avoid the linebreak issue, but your other question is not clear. Please define clearly the patterns you WANT to match, and the patterns you DO NOT WANT to match. ETC is not a helpful descriptor. But to match combinations of numbers, digits, optional leading +, parentheses, dashes and spaces, limited to 6-20 characters, you could use: **\+?((?=[-0-9() ]).){6,20}** But I'm not sure that's what really what you want. – Ron Rosenfeld Aug 17 '14 at 20:43
  • do you really need to validate them at all? there are ones less than 6 and greater than 20, would it hurt to let the user type what they want to. –  Aug 17 '14 at 20:44
  • 1
    You can replace `\s` with `\h` that matches only horizontal spaces. – Casimir et Hippolyte Aug 17 '14 at 21:19
  • @Ron Rosenfeld Your regex is nice, thanks, but it also matches leading and trailing spaces. I edited my 2nd question to make clearer what I'm looking for... – Pingui Aug 18 '14 at 09:20
  • 1
    @bromelio Now that your requirements are more clear, merely define the first and last characters as being whatever, and adjust the length of the "inbetween" portion appropriately – Ron Rosenfeld Aug 18 '14 at 10:40
  • When you used `\r\n` in your pattern, did you wrap your pattern in single quotes or double quotes? – mickmackusa May 03 '23 at 13:06

1 Answers1

1

\s means: match any whitespace character. just replace it with a simple white space ' '

/(\+|0|\()[\d() -]{6,20}\d/g

see this demo

Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33
Ghilas BELHADJ
  • 13,412
  • 10
  • 59
  • 99