2

The following regex

(\d{3,4})

matches 1234 in

123456, but since 123456 is longer than 4, I don't want the regex to match anything.

These are my 3 regular expressions that I am using separately, I tried combining them, but it returns more than 2 groups and I just need 2 at the most.

//Match card number before security code
(?<!\d)(\d{13,16})(?!\d)[<""'].*?(?=[>""']\d{3,4}[<""'])[>""'](?<!\d)(\d{3,4})(?!\d)[<""']

//Match card number after security code
(?<!\d)(\d{3,4})(?!\d)[<""'].*?(?=[>""']\d{13,16}[<""'])[>""'](?<!\d)(\d{13,16})(?!\d)[<""']

//Match just card number
(?<!\d)(\d{13,16})(?!\d)
Xaisoft
  • 45,655
  • 87
  • 279
  • 432

3 Answers3

4

Yup

(?<!\d)(\d{3,4})(?!\d)

should do the trick. Since the ?<! and ?! assertions are zero-width, they don't actually match anything (they just check the parse state against the input at the current position). So you could just as well say

((?<!\d)\d{3,4}(?!\d))

if you preferred.


See http://www.regular-expressions.info/refadv.html

(?!regex)

Zero-width negative lookahead. Identical to positive lookahead, except that the overall match will only succeed if the regex inside the lookahead fails to match.

sehe
  • 374,641
  • 47
  • 450
  • 633
  • This confused me at first, but then I got it. Basically your looking back and forward to make sure no digits exist, right? – Xaisoft Jan 31 '12 at 21:37
  • My original regex is more complex, but I can't figure out how to only return 2 groups even if I have 6 specified in my expression. I basically want to do an OR on the groups – Xaisoft Jan 31 '12 at 21:38
  • @Xaisoft: please explain your actual problem. What do you mean by "groups"? – Borodin Jan 31 '12 at 21:43
  • @Xaisoft it would help if you updated the question describing what the 'groups' are and what you mean by `do an OR on the groups`. Regardless, does `(\d{4}|\d{3})` help? Perhaps even repeatedly and asserting no adjacent digits: `(?<!\d)(\d{4}|\d{3})+(?!\d)` ? – sehe Jan 31 '12 at 21:45
  • @sehe - I have a question already, but haven't got much help. Right now I am using three reqular expressions. Here is the link: http://stackoverflow.com/questions/9039998/combine-a-positive-lookahead-and-negative-lookahead/9041049#comment11342953_9041049 – Xaisoft Jan 31 '12 at 21:47
1

Use \b to mark the beginning and end of the string, a la

\b\d{3,4}\b

eouw0o83hf
  • 9,438
  • 5
  • 53
  • 75
0

Try this: (\b\d{3,4}\b) The \b character means word boundary. if you just want any non-digit characters, try \D(\d{3,4})\D

mklauber
  • 1,126
  • 10
  • 19