javascript - javascript 中的正则表达式和字符串有什么区别?

标签 javascript regex

> "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/

相关文章:

复杂字符之间的 Java 正则表达式文本

regex - 使用正则表达式验证数据是否正确?

javascript - ng-repeat 中缺少的元素

javascript - 检索 HTML 元素的位置 (X,Y)

java - Android正则表达式分割成字符串数组

Java转义正则表达式元字符和构造

javascript - 发送电子邮件时出现 Node.js 404 错误,忽略了我的 res.status

javascript - 文本转语音库(暂停问题)

javascript - 日期对象的类型

c# - 不破坏 html c# 的子字符串