Home > Blockchain >  Regex pattern to capture numbers only, but only on single line
Regex pattern to capture numbers only, but only on single line

Time:09-27

This regex pattern that will match 15 consecutive numbers, optionally with non-digits interspersed:

\d(?:\D?\d){14}(?!\d)

Here is my sample data showing four valid matches:

Correct matches: #19-04-052-320-008-55,19 04 052 320 008 75,19/04/052/320/0/0/8/8/0, 190405232000895 

The problem arises when there are digits across multiple lines. My regex will match the multi-line string below:

Incorrect match:
12
950,500
345
817,430
67

How can I modify the current pattern so that it will not match 15 consecutive numbers when they are spread over multiple lines?

CodePudding user response:

You may use this regex:

\b\d(?:[^\n\d]*\d){14}(?!\d)

RegEx Demo

RegEx Breakup:

  • \b: Matches a word boundary so that first match digit is matched in a separate word
  • [^\n\d]*: Matches 0 or more of any char that is not a digit and not a line break
  • (?:[^\n\d]*\d){14}: Matches 14 digits optionally interspersed by 0 or more non-digits, non-line breaks
  • Related