0

Example string

fgcfghhfghfgch1234567890fghfghfgh fhghghfgh+916546546165fghfghfghfgh fhfghfghfghfgh+915869327425ghfghfghfgh

I want to match

1234567890
6546546165
5869327425

In essence i would like to do something like this (?<=\+\d{2})?\d{10}. Match 10 digits \d{10} which may follow ? a country code in format: \+\d{2}. What would be a correct regular expression to do this?

Also, What to do if the country code could possibly be even 3 digit long. e.g.

+917458963214
+0047854123698 

match 7854123698 and 7458963214.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    You should use a captuirng group here, `(?:\+\d{2,3})?(\d{10})`. Or, use `\K`, `(?:\+\d{2,3})?\K\d{10}`. See [demo](https://regex101.com/r/OnDxUA/1). Add `(?!\d)` at the end and replace `(?:\+\d{2,3})?` with `(?:\+\d{2,3}|(?<!\d))` to ensure you fail the match if there are more than 10 digits. – Wiktor Stribiżew Sep 26 '20 at 14:09
  • This Java example will handle any phone number, all you need to do is to add the variations want to match. See: https://stackoverflow.com/questions/123559/how-to-validate-phone-numbers-using-regex/63771966#63771966 – DigitShifter Sep 26 '20 at 14:30

1 Answers1

0

Your expected matches all appear to be immediately followed with a char other than a digit.

I suggest making the pattern inside the positive lookbehind optional and adding (?!\d) lookahead at the end to fail the match (and thus triggering backtracking in the lookbehind) if the ten digits are immediately followed with a digit:

(?<=(?:\+\d{2,3})?)\d{10}(?!\d)

See the regex demo. Details:

  • (?<=(?:\+\d{2,3})?) - a positive lookbehind that requires + and two or three digits or an empty string immediately to the left of the current location
  • \d{10} - ten digits
  • (?!\d) - no digit allowed immediately on the right.

However, as in 99% you can access captured substrings, you should just utilize a capturing group:

(?:\+\d{2,3})?(\d{10})

See this regex demo. Your values are in Group 1.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563