简体   繁体   English

Javascript-正则表达式引号的奇数

[英]Javascript - regex odd number of quotes

So I have this javascript regex expression: 所以我有这个javascript正则表达式:

var reg = new RegExp("(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))");

How could I escape the quotes so that the quotes are contained, since right now, they overflow, and quote the lines after it. 我该如何转义引号,以便包含引号,因为现在它们会溢出,并在引号后加引号。

Edit: regex expanded: 编辑:正则表达式扩展:

(?xi)
\b
(                           # Capture 1: entire matched URL
  (?:
    [a-z][\w-]+:                # URL protocol and colon
    (?:
      /{1,3}                        # 1-3 slashes
      |                             #   or
      [a-z0-9%]                     # Single letter or digit or '%'
                                # (Trying not to match e.g. "URI::Escape")
    )
    |                           #   or
    www\d{0,3}[.]               # "www.", "www1.", "www2." … "www999."
    |                           #   or
    [a-z0-9.\-]+[.][a-z]{2,4}/  # looks like domain name followed by a slash
  )
  (?:                           # One or more:
    [^\s()<>]+                      # Run of non-space, non-()<>
    |                               #   or
    \(([^\s()<>]+|(\([^\s()<>]+\)))*\)  # balanced parens, up to 2 levels
  )+
  (?:                           # End with:
    \(([^\s()<>]+|(\([^\s()<>]+\)))*\)  # balanced parens, up to 2 levels
    |                                   #   or
    [^\s`!()\[\]{};:'".,<>?«»“”‘’]        # not a space or one of these punct chars
  )
)

If you just use the native declaration form of regex in javascript: 如果您仅在javascript中使用正则表达式的本机声明形式:

var reg = /regex here/;

Then, you can freely use quotes in the regex without escaping anything. 然后,您可以在正则表达式中自由使用引号,而无需转义任何内容。 You will have to escape any forward slashes in the regex by putting a backslash in front of it. 您必须通过在正则表达式前面加上反斜杠来转义正斜杠。

If you want to stick with the string form, then you can escape a quote with a backslash in front of it to keep it from being a string terminator: 如果要坚持使用字符串形式,则可以在引号前面加上反斜杠,以防止其成为字符串终止符:

var reg = new RegExp('My dog\'s breath');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM