[英]Regex to match 1 or less occurrence of string?
Suppose I want a regex to match "Jump over this bridge FOOL" as well as "Jump over this bridge".假设我想要一个正则表达式来匹配“跳过这座桥 FOOL”和“跳过这座桥”。 How do I make "FOOL" optional (0 or 1 occurrence)?如何使“FOOL”可选(0 或 1 次)?
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:标记以将组的出现指定为可选(出现 0 或 1 次),或者您也可以使用花括号将最小值/最大值设为 0 和 1,因此答案是:
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.如果您想匹配包含FOOL
少于两次的任何字符串,事情会变得有点复杂。 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
.这将逻辑颠倒过来,并断言该字符串不包含 2 个(或更多) FOOL
实例。
Try doing this :尝试这样做:
Jump over this bridge( FOOL)?
You can put a set of strings too :您也可以放置一组字符串:
Jump over this bridge( FOOL| FOOB)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.