如何使正则表达式的一部分成为可选的? [英] How can I make part of regex optional?
问题描述
假设我有以下正则表达式匹配末尾带有分号的字符串:
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:
"";
我试过用这个:
\".+?\";
但这没有用.
我的问题是,如何使 .+
成为可选的一部分,以便用户不必在字符串中放入任何字符?
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?
推荐答案
要使 .+
成为可选项,您可以这样做:
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.
或者,您可以这样做:
\".*?\";
.*
会贪婪地匹配任何字符零次或多次.在 *
之后添加 ?
强制正则表达式引擎进行尽可能短的匹配.
.*
would match any character zero or more times greedily. Adding ?
after the *
forces the regex engine to do a shortest possible match.
这篇关于如何使正则表达式的一部分成为可选的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!