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)?
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}
You might want to have a look at a regex tutorial .
Optional parts of a regex are indicated with a question mark:
Jump over this bridge( FOOL)?
In case you want to match any string that includes FOOL
less than twice, things get a bit more complicated. Then you would be best off using the more advanced concept of a negative lookahead :
^(?!(.*FOOL){2})
This turns the logic on its head and asserts that the string doesn't contain 2 (or more) instances of FOOL
.
Try doing this :
Jump over this bridge( FOOL)?
You can put a set of strings too :
Jump over this bridge( FOOL| FOOB)?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.