1

I am trying to merge below four pattern into single pattern using pipe(|), but not getting the required result.

Scenario:

  • max 7 entry(alphabet and digits)
  • should contain 4 and only 4 consecutive digits(mandatory)

Patterns:

([\d]{4}[a-zA-Z]{0,3})
[a-zA-Z]{0,1}[\d]{4}[a-zA-Z]{0,2}
[a-zA-Z]{0,2}[\d]{4}[a-zA-Z]{0,1}
[a-zA-Z]{0,3}[\d]{4})
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
Rituja
  • 21
  • 1

1 Answers1

0

You can use

^(?=[a-zA-Z\d]{4,7}$)[a-zA-Z]*\d{4}[a-zA-Z]*$

See the regex demo

If you are using the regex pattern in a method that anchors the pattern by default, the ^ and/or $ might be redundant, but will still work.

The regex breakdown:

  • ^ - start of string
  • (?=[a-zA-Z\d]{4,7}$) - the positive lookahead requiring the string to only consist of 4 to 7 letters or digits
  • [a-zA-Z]*\d{4}[a-zA-Z]* - the string should contain 4 digits (\d{4}`) that can be preceded or followed with zero or more letters
  • $ - end of string.
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • Thanks Wiktor..Its working for me. Can you help me to know the best resource for regex pattern? I know the basic only.It will be really helpful if you know about any resource having some detailed info. – Rituja Mar 14 '16 at 13:38
  • I can only suggest doing all lessons at [regexone.com](http://regexone.com/), reading through [regular-expressions.info](http://www.regular-expressions.info), [regex SO tag description](http://stackoverflow.com/tags/regex/info) (with many other links to great online resources), and the community SO post called [What does the regex mean](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean). – Wiktor Stribiżew Mar 14 '16 at 13:39