我想捕获一些字符串,只有当它出现,所以我使用?
捕获后()
意思是我想捕获那部分字符串,但它不必显示(零或一)但是当我()
之后添加?
拖放那场比赛:括号后面的javascript正则表达式问号
var str = 'blablablacaptureblablabla';
,如果我做一个普通捕获与()
我得到的欲望捕获:
console.log(str.match(/.*(capture).*/i)); // array[1] = capture
如果我添加?
来表示捕获可能是或不是我所能得到的undefined:
console.log(str.match(/.*(capture)?.*/i)); // array[1] = undefined
这是为什么?所有我想要的是捕获字capture
是否其存在与否的字符串因此这将不会返回null:
var str = 'blablablalablabla'; //string without word 'capture'
console.log(str.match(/.*(capture)?.*/i)); // this will work but if i use it with string with the word 'capture' it won't capture the 'capture'
编辑:
只要是明确的 - 我想这个字符串blablacaptureblabla
到捕捉字capture
,也该字符串blablablabla
不返回null,因为我使用?
这意味着零或一个
你的意思'的console.log ;'?因此,如果输入中不存在“capture”,组1总是使用空字符串进行初始化? –
如果你移动捕获组圆括号内的'?',它会起作用:'console.log(str.match(/.*(capture?)。*/i));' –
@StephenP - 但是如果我用它字符串没有捕获像'blablablalablabla'这样的字,它会在匹配时返回'null' - 这不是我想要的,因为我想要零或一个('?') – Adidi