简体   繁体   中英

Regex to match string 2 times but not 3

I try to regex match string like these examples:

NetTAP IPX C-4-16

SmartTAP DP6409 Dual E1-11-16

but not these ones:

NetTAP IPX C-4-16-0

SmartTAP DP6409 Dual E1-11-16-0

SYSTEM

I've tried some solutions without success.

My idea was to search the -\d\d 2 times but not 3 times

(?!\-\d+)(\-\d+){2}$

or

[^(\-\d+)](\-\d+){2}$

Could you help me?

You can use

(?<!-\d+)(?:-\d+){2}$

See the regex demo . Details :

  • (?<!-\d+) - a negative lookbehind that fails the match if there is a - char and one or more digits immediately to the left of the current location
  • (?:-\d+){2} - two repetitions of - and one or more digits
  • $ - end of string.

You can also match 3 times what you want to avoid, and capture 2 times what you want to keep using a capture group.

(?:-\d+){3}$|(-\d+-\d+)$

The pattern matches:

  • (?:-\d+){3}$ Match 3 repetitions at the end of the string
  • | Or
  • (-\d+-\d+)$ capture 2 repetitions at the end of the string in group 1

Regex demo

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