是否可以使用另一个正则表达式检测有效的正则表达式?如果是这样,请提供示例代码如下。
- /
- ^ # start of string
- ( # first group start
- (?:
- (?:[^?+*{}()[\]\\|]+ # literals and ^,$
- | \\. # escaped characters
- | \[ (?: \^?\\. | \^[^\\] | [^\\^] ) # character classes
- (?: [^\]\\]+ | \\. )* \]
- | \( (?:\?[:=!]|\?<[=!]|\?>)? (?1)?? \) # parenthesis,with recursive content
- | \(\? (?:R|[+-]?\d+) \) # recursive matching
- )
- (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers
- | \| # alternative
- )* # repeat content
- ) # end first group
- $ # end of string
- /
这是一个递归正则表达式,并且不受许多正则表达式引擎支持。基于PCRE的应该支持它。
没有空格和注释:
- /^((?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>)?(?1)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*)$/
.NET不直接支持递归。 ((?1)和(?R)构造)。递归必须转换为计数平衡组:
- ^ # start of string
- (?:
- (?: [^?+*{}()[\]\\|]+ # literals and ^,$
- | \\. # escaped characters
- | \[ (?: \^?\\. | \^[^\\] | [^\\^] ) # character classes
- (?: [^\]\\]+ | \\. )* \]
- | \( (?:\?[:=!]
- | \?<[=!]
- | \?>
- | \?<[^\W\d]\w*>
- | \?'[^\W\d]\w*'
- )? # opening of group
- (?<N>) # increment counter
- | \) # closing of group
- (?<-N>) # decrement counter
- )
- (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers
- | \| # alternative
- )* # repeat content
- $ # end of string
- (?(N)(?!)) # fail if counter is non-zero.
压缩:
- ^(?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>|\?<[^\W\d]\w*>|\?'[^\W\d]\w*')?(?<N>)|\)(?<-N>))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*$(?(N)(?!))