Commenting Regular Expressions

后端 未结 4 1312
忘掉有多难
忘掉有多难 2020-11-29 11:14

I\'m trying to comment regular expressions in JavaScript.

There seems to be many resources on how to remove comments from code using regex, but not actuall

4条回答
  •  天涯浪人
    2020-11-29 11:51

    In several other languages (notably Perl), there's the special x flag. When set, the regexp ignores any whitespace and comments inside of it. Sadly, javascript regexps do not support the x flag.

    Lacking syntax, the only way to leverage readability is convention. Mine is to add a comment before the tricky regular expression, containing it as if you've had the x flag. Example:

    /*
      \+?     #optional + sign
      (\d*)   #the integeric part
      (       #begin decimal portion
         \.
         \d+  #decimal part
      )
     */
    var re = /\+?(\d*)(\.\d+)/;
    

    For more complex examples, you can see what I've done with the technique here and here.

提交回复
热议问题