regex – 是否有正则表达式来检测有效的正则表达式?

前端之家收集整理的这篇文章主要介绍了regex – 是否有正则表达式来检测有效的正则表达式?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以使用另一个正则表达式检测有效的正则表达式?如果是这样,请提供示例代码如下。
  1. /
  2. ^ # start of string
  3. ( # first group start
  4. (?:
  5. (?:[^?+*{}()[\]\\|]+ # literals and ^,$
  6. | \\. # escaped characters
  7. | \[ (?: \^?\\. | \^[^\\] | [^\\^] ) # character classes
  8. (?: [^\]\\]+ | \\. )* \]
  9. | \( (?:\?[:=!]|\?<[=!]|\?>)? (?1)?? \) # parenthesis,with recursive content
  10. | \(\? (?:R|[+-]?\d+) \) # recursive matching
  11. )
  12. (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers
  13. | \| # alternative
  14. )* # repeat content
  15. ) # end first group
  16. $ # end of string
  17. /

这是一个递归正则表达式,并且不受许多正则表达式引擎支持。基于PCRE的应该支持它。

没有空格和注释:

  1. /^((?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>)?(?1)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*)$/

.NET不直接支持递归。 ((?1)和(?R)构造)。递归必须转换为计数平衡组:

  1. ^ # start of string
  2. (?:
  3. (?: [^?+*{}()[\]\\|]+ # literals and ^,$
  4. | \\. # escaped characters
  5. | \[ (?: \^?\\. | \^[^\\] | [^\\^] ) # character classes
  6. (?: [^\]\\]+ | \\. )* \]
  7. | \( (?:\?[:=!]
  8. | \?<[=!]
  9. | \?>
  10. | \?<[^\W\d]\w*>
  11. | \?'[^\W\d]\w*'
  12. )? # opening of group
  13. (?<N>) # increment counter
  14. | \) # closing of group
  15. (?<-N>) # decrement counter
  16. )
  17. (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers
  18. | \| # alternative
  19. )* # repeat content
  20. $ # end of string
  21. (?(N)(?!)) # fail if counter is non-zero.

压缩:

  1. ^(?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>|\?<[^\W\d]\w*>|\?'[^\W\d]\w*')?(?<N>)|\)(?<-N>))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*$(?(N)(?!))

猜你在找的正则表达式相关文章