Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make part of regex optional?

Tags:

Suppose I have the following regex that matches a string with a semicolon at the end:

\".+\"; 

It will match any string except an empty one, like the one below:

""; 

I tried using this:

\".+?\"; 

But that didn't work.

My question is, how can I make the .+ part of the, optional, so the user doesn't have to put any characters in the string?

like image 229
Ethan Bierlein Avatar asked Oct 02 '14 12:10

Ethan Bierlein


People also ask

How do I exclude a regex match?

To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself.

How do I make a group optional in regex python?

So to make any group optional, we need to have to put a “?” after the pattern or group. This question mark makes the preceding group or pattern optional. This question mark is also known as a quantifier.

What is ?! In regex?

The ?! n quantifier matches any string that is not followed by a specific string n.


1 Answers

To make the .+ optional, you could do:

\"(?:.+)?\"; 

(?:..) is called a non-capturing group. It only does the matching operation and it won't capture anything. Adding ? after the non-capturing group makes the whole non-capturing group optional.

Alternatively, you could do:

\".*?\"; 

.* would match any character zero or more times greedily. Adding ? after the * forces the regex engine to do a shortest possible match.

like image 70
Avinash Raj Avatar answered Sep 17 '22 13:09

Avinash Raj