Home > Back-end >  How to match and extract string matching regular expression
How to match and extract string matching regular expression

Time:07-16

This is main string:

MR HI Government He PIHe9 Hanumana Ji 3-� fafer/ DOB : 01/01/1959 989 / Male 2094 7051 9541 ������ - ��� ����� �� 3�1���

I want to match and extract 2094 7051 9541 using regular expression

and regex pattern to find is:

^[2-9]{1}[0-9]{-3}\\s[0-9]{4}\\s[0-9]{4}$

I want to use javascript to match and extract string. But not able to find right syntax to it.

Any help would be appreciated.

Thanks, PD

CodePudding user response:

You can use

const regex = /\b[2-9]\d{3}\s\d{4}\s\d{4}\b/;

See the regex demo. Note the use of a regex literal that helps avoid double escaping backslashes.

Details

  • \b - a word boundary
  • [2-9] - a digit from 2 to 9
  • \d{3} - three digits
  • \s - a wjitespace
  • \d{4} - four digits
  • \s - a whitespace
  • \d{4} - four digits
  • \b - a word boundary.

The word boundaries avoid matching the number as part of another number/word.

  • Related