InFlames82
InFlames82

Reputation: 513

Regex with wildcard search?

I created a Regex to check a string for the following situation:

ie: 1234.123.125B

My Regex: ^[0-9]{4}[.][0-9]{3}[.][0-9a-zA-Z]{4,8}$

But now I need a wildcard search: The Regex should also match if there is a '*' after the first 8 characters. For example:

1234.123.12*   MATCH
1234.123*      MATCH
1234.123.45B9* MATCH
1234.12*       NO MATCH
1234.12345*    NO MATCH

How can I add the wildcard search to my Regex? Thank you

Upvotes: 2

Views: 4315

Answers (2)

JvdV
JvdV

Reputation: 75870

My assumptions are that:

  • You don't allow wildcards to be mid-string
  • Nor do you want to allow wildcards after the full pattern (e.g.: 1234.123.12345678*).

So, alternatively you may possibily use something like:

^\d{4}\.\d{3}(?!.*\*.)(?![^*]{0,4}$)[.*][*\da-zA-Z]{0,8}$

See the online demo.


  • ^ - Start string ancor.
  • \d{4}\.\d{3} - Four digits, a dot and another three digits.
  • (?!.*\*.) - Negative lookahead for zero or more characters followed by asterisk and another character other than newline.
  • (?![^*]{0,4}$) - Negative lookahead for zero to four characters other than asterisk before end string ancor.
  • [.*] - A literal dot or asterisk.
  • [*\da-zA-Z]{0,8} - Zero to eight characters from the character class.
  • $ - End string ancor.

Upvotes: 0

anubhava
anubhava

Reputation: 785316

You may use this regex with alternation:

^\d{4}\.\d{3}(?:\*|\.[\da-zA-Z]{0,7}\*|\.[\da-zA-Z]{4,8})$

RegEx Demo

RegEx Details:

  • ^: Start
  • \d{4}\.\d{3}: Match 4 digits + 1 dot + 3 digits
  • (?:\*|\.[\da-zA-Z]{0,7}\*|\.[\da-zA-Z]{4,8}): matches a single * OR a * after after a dot and 0 to 7 digits/letters OR match 4 to 8 digits/letters
  • $: End

Upvotes: 4

Related Questions