Rodrigo Gomes
Rodrigo Gomes

Reputation: 134

Regex negation for two consecutive numbers

I'm trying to create a regex that blew my mind. How do I make the regex negation below when I have two consecutive numbers?

/^([\p{L}\p{N}\. ]+)(, ?| )([0-9-]+[a-z]?)(, ?| |$)(.*)/iu

Valid examples:

Text Text 123 anything
Text Text, 123, anything
Text Text 123B anything
Text Text, 123B, anything
Text 123 anything
Text 123B anything
Text, 123, anything
Text, 123B, anything
987 123 anything
987 123B anything
987, 123, anything
987, 123B, anything

(Need to be) Invalid examples:

Text Text 456 123 anything
Text Text, 456, 123, anything
Text Text 456 123B anything
Text Text, 456, 123B, anything
Text 456 123 anything
Text 456 123B anything
Text, 456, 123, anything
Text, 456, 123B, anything
987 456 123 anything
987 456 123B anything
987, 456, 123, anything
987, 456, 123B, anything

But as you guys can see, all the examples above are valid for my regex: https://regex101.com/r/6t5Oq5/4

Requirements: The first group may have letters or numbers. The second group can have numbers or numbers followed by a letter, and the third group can have anything. All groups can be separated by commas or space. And all letters and numbers can be any size. There can not be consecutive numbers in the string, unless the number is in the first group or in the last group (anything).

What is the best way to do this?

Upvotes: 0

Views: 456

Answers (2)

alpha bravo
alpha bravo

Reputation: 7948

Based on what you posted, use this Pattern ^(\S+)(?=[^\d\r\n]+\d+[^\d\r\n]+$).* Demo

^                       # Start of string/line
(                       # Capturing Group (1)
  \S                    # <not a whitespace character>
  +                     # (one or more)(greedy)
)                       # End of Capturing Group (1)
(?=                     # Look-Ahead
  [^\d\r\n]             # Character not in [\d\r\n] Character Class
  +                     # (one or more)(greedy)
  \d                    # <digit 0-9>
  +                     # (one or more)(greedy)
  [^\d\r\n]             # Character not in [\d\r\n] Character Class
  +                     # (one or more)(greedy)
  $                     # End of string/line
)                       # End of Look-Ahead
.                       # Any character except line break
*                       # (zero or more)(greedy)

Upvotes: 2

Bananaapple
Bananaapple

Reputation: 3114

Not 100% sure on the required rules of yours but this here regex matches the first but not the second block:

/^([a-z0-9]+,? )([0-9]+[a-z]?,? )([a-z0-9]+)$/

Demo here: http://regexr.com/3gjd7

Upvotes: 2

Related Questions