Regex, how to combine an optional character

I have a regex that I thought was working correctly so far. I need to match an optional character. He may or may not be there.

Here are two lines. The top line is matched, but the bottom is not. The absence of a single letter in the bottom line is what makes it unsuccessful.

I would like to receive one letter after the starting 5 digits, if there is one, and if not, continue to receive the rest of the line. This letter may be AZ .

If I delete ([AZ]{1}) +.*? + ([AZ]{1}) +.*? + from a regular expression, it will match everything I need, except for the letter, but this is important.

 20000 K Q511195DREWBT E00078748521 30000 K601220PLOPOH Z00054878524 

Here is the regex that I use.

 /^([0-9]{5})+.*? ([AZ]{1}) +.*? +([AZ]{1})([0-9]{3})([0-9]{3})([AZ]{3})([AZ]{3}) +([AZ])[0-9]{3}([0-9]{4})([0-9]{2})([0-9]{2})/ 
+88
operators string regex
Oct 24 2018-10-10T00:
source share
4 answers

Using

 [AZ]? 

to make the letter optional. {1} is redundant. (Of course, you could also write [AZ]{0,1} , which would mean the same, but what does it exist for ? )

You can improve your regular expression to

 ^([0-9]{5})+\s+([AZ]?)\s+([AZ])([0-9]{3})([0-9]{3})([AZ]{3})([AZ]{3})\s+([AZ])[0-9]{3}([0-9]{4})([0-9]{2})([0-9]{2}) 

And, since in most dialects of regex, \d same as [0-9] :

 ^(\d{5})+\s+([AZ]?)\s+([AZ])(\d{3})(\d{3})([AZ]{3})([AZ]{3})\s+([AZ])\d{3}(\d{4})(\d{2})(\d{2}) 

But: do you really need 11 separate capture groups? And if so, why don't you take the fourth or last group of numbers?

+163
Oct 24 '10 at 6:44
source share

Can you make one letter optional by adding ? after it as:

 ([AZ]{1}?) 

The quantifier {1} is redundant, so you can remove it.

+14
Oct 24
source share

You should also mark one letter as optional:

 ([AZ]{1})? +.*? + 

or make the full part optional

 (([AZ]{1}) +.*? +)? 
+5
Oct 24 '10 at 6:44
source share

You can also use a simpler regular expression designed for your case, for example (.*)\/(([^\?\n\r])*) where $2 matches what you want.

0
Feb 06 '19 at 15:43
source share



All Articles