-2

I need regex to return invalid on a match. Specifically, the match is a string that starts with an A or an M and is followed by four numbers ie, A1223. The four numbers could be any random sequence.

I'm sure lookarounds are the way to handle this but I haven't grasped regex as a concept just yet. Thus far I've discovered how to capture the matched strings separate from other strings with the following.

([\s\S]*?)(A[\d][\d][\d][\d]|M[\d][\d][\d][\d])

Appreciate the help.

  • You need to provide some sample data, indicating which should and which should not be matched. It's unclear what exactly you mean by *return invalid on a match*. Do you want it to return false if there is a match and true if there is not? Or return true if there is a match and false if not? Are you trying to capture the part that consists of an A or M followed by 4 digits? Or capture the parts around it? Or something else entirely? Also, what regex flavor are you using? – Ken White May 05 '16 at 00:10

2 Answers2

0

Regex doesn't really have match negation, but you can (ab)use a negative lookahead assertion to do inverted matching:

^((?!\s[AM]\d{4}).){6}
Community
  • 1
  • 1
Mathias R. Jessen
  • 106,010
  • 8
  • 112
  • 163
0

to match all strings not starting with A or M followed by 4 digits:

with negative lookahead:

^(?![AM]\d{4}).* 

with consuming pattern using () capture groups:

[AM]\d{4}.*|(.+) 
Scott Weaver
  • 6,328
  • 2
  • 23
  • 37