我正在尝试制作一个 JS 正则表达式,它在所有这些输入字符串中返回 example
,其中可能包含问号。
示例?之后?之后
example?after
例子?
示例
example
将是一个动态字符串,因此我无法逐字匹配字符串“example”。
'example?after?after'.match(/(.*?)\?/)[1]
'example?after'.match(/(.*?)\?/)[1]
'example?'.match(/(.*?)\?/)[1]
'example'.match(/(.*?)\?/)[1]
上面的前 3 个按预期返回 example
但最后一个给出错误。如何修改正则表达式以返回预期结果?
最佳答案
你可以使用
/^[^?]+/
参见 regex demo
^
匹配字符串的开头,[^?]+
匹配除?
之外的一个或多个符号。
var regex = /^[^?]+/;
var strs =[ 'example?after?after', 'example?after', 'example?', 'example'];
for (var s of strs)
{
console.log(s + " => " + s.match(regex));
}
关于javascript - 如何匹配可能有或没有后缀的 JS 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40159276/