> "1fff=*; style=mobile".match("[\s]*")
[ '', index: 0, input: '1fff=*; style=mobile' ]
> "1fff=*; style=mobile".match("[^;]*")
[ '1fff=*', index: 0, input: '1fff=*; style=mobile' ]
> "1fff=*; style=mobile".match('(^|;)[\s]*style=([^;]*)')
null
> "1fff=*; style=mobile".match(/(^|;)[\s]*style=([^;]*)/)
[ '; style=mobile',
';',
'mobile',
index: 6,
input: '1fff=*; style=mobile' ]
str.match(str)
可以部分作为正则表达式模式工作,但有一些区别。
到底有什么区别?
最佳答案
区别在于,在字符串文字中,\s
仅表示 s
— 字符串文字没有 \s
转义序列,因此 \
被删除。
如果您想使用字符串文字,并且需要正则表达式包含 \s
,则字符串文字需要包含 \\s
(带有额外的反斜杠),因此字符串将包含 \s
:
> "1fff=*; style=mobile".match('(^|;)[\\s]*style=([^;]*)')
; style=mobile,;,mobile
(不过,我建议坚持使用正则表达式。)
关于javascript - javascript 中的正则表达式和字符串有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29948710/