[regex] Regex how to match an optional character

I have a regex that I thought was working correctly until now. I need to match on an optional character. It may be there or it may not.

Here are two strings. The top string is matched while the lower is not. The absence of a single letter in the lower string is what is making it fail.

I'd like to get the single letter after the starting 5 digits if it's there and if not, continue getting the rest of the string. This letter can be A-Z.

If I remove ([A-Z]{1}) +.*? + from the regex, it will match everything I need except the letter but it's kind of important.

20000      K               Q511195DREWBT            E00078748521
30000                      K601220PLOPOH            Z00054878524

Here is the regex I'm using.

/^([0-9]{5})+.*? ([A-Z]{1}) +.*? +([A-Z]{1})([0-9]{3})([0-9]{3})([A-Z]{3})([A-Z]{3}) +([A-Z])[0-9]{3}([0-9]{4})([0-9]{2})([0-9]{2})/

This question is related to regex string operators

The answer is


You can make the single letter optional by adding a ? after it as:

([A-Z]{1}?)

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


You have to mark the single letter as optional too:

([A-Z]{1})? +.*? +

or make the whole part optional

(([A-Z]{1}) +.*? +)?

You also could use simpler regex designed for your case like (.*)\/(([^\?\n\r])*) where $2 match what you want.


Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to operators

What is the difference between i = i + 1 and i += 1 in a 'for' loop? Using OR operator in a jquery if statement What is <=> (the 'Spaceship' Operator) in PHP 7? What does question mark and dot operator ?. mean in C# 6.0? Boolean operators ( &&, -a, ||, -o ) in Bash PowerShell and the -contains operator How do I print the percent sign(%) in c Using the && operator in an if statement What do these operators mean (** , ^ , %, //)? How to check if div element is empty