Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match 1 or less occurrence of string?

Tags:

regex

Suppose I want a regex to match "Jump over this bridge FOOL" as well as "Jump over this bridge". How do I make "FOOL" optional (0 or 1 occurrence)?

like image 470
Henley Avatar asked Nov 13 '12 01:11

Henley


People also ask

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What is used for zero or more occurrences in regex?

You can repeat expressions with an asterisk or plus sign. A regular expression followed by an asterisk ( * ) matches zero or more occurrences of the regular expression. If there is any choice, the first matching string in a line is used.

What do you mean by O or 1 character?

When a character is followed by ? in a regular expression it means to match zero or one instance of the character. So X? matches an 'X' if there is one in the string, but otherwise matches nothing.


1 Answers

You can use the ? mark to specify the occurrence of a group as optional (occurs 0 or 1 time), or you can also use curly braces with min/max values as 0 and 1, so the answer is:

Jump over this bridge( FOOL)? 

or

Jump over this bridge( FOOL){0,1} 
like image 150
Santosh Kaparthi Avatar answered Oct 04 '22 12:10

Santosh Kaparthi