简体   繁体   中英

regex pattern to match specific number pattern , skip if there different pattern

Requirement:

If pattern 57XXXXXXX OR 57XXXXXXX-X found in a sentence , then copy this matched pattern ( X - denotes 7 integer number and 57 are constant values must be there), else ignore complete sentence.

I have written a regex pattern 57[0-9]{7}|-[0-9]{1} to do match both the pattern.

If below pattern found(8 digits after 57 instead 7 , then still above regex still gets the matching pattern (actually expecting regex to not match)

for eg 5712345678-0 (after 57 , 8 digits in sentance) --> regex matches and gives 571234567-0

Using java to compile above pattern.

You could try this:

\b57\d{7}(?:-\d)?\b

Here's what it looks like:

正则表达式可视化

In Java, that would be Pattern.compile("\\\\b57\\\\d{7}(?:-\\\\d)?\\\\b") .

差别不大但允许字母和下划线:

(?:(?<=[^0-9])|^)57[0-9]{7}(?:-[0-9])?(?:(?=[^0-9])|$)

You could use lookahead assertions in this case.

57\d{7}(?:-\d)?(?!\d)

Regular expression:

57              '57'
 \d{7}          digits (0-9) (7 times)
     (?:        group, but do not capture:
       -        '-'
       \d       digits (0-9)
     )?         end of grouping
      (?!       look ahead to see if there is not:
        \d      digits (0-9)
      )         end of look-ahead

Or:

(?:57\d{7})(?:-\d)?(?!\d)

Regular expression:

(?:             group, but do not capture:
  57            '57'
   \d{7}        digits (0-9) (7 times)
)               end of grouping
 (?:            group, but do not capture
   -            '-'
    \d          digits (0-9)
 )?             end of grouping
  (?!           look ahead to see if there is not:
    \d          digits (0-9)
  )             end of look-ahead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM