加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 00:38:59 所属栏目:百科 来源:网络整理
导读:是否可以使用另一个正则表达式检测有效的正则表达式?如果是这样,请提供示例代码如下。 /^ # start of string( # first group start (?: (?:[^?+*{}()[]|]+ # literals and ^,$ | . # escaped characters | [ (?: ^?. | ^[^] | [^^] ) # char
是否可以使用另一个正则表达式检测有效的正则表达式?如果是这样,请提供示例代码如下。
/
^                                             # 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
        (?: [^]]+ | . )* ]
   | ( (?:?[:=!]
         | ?<[=!]
         | ?>
         | ?<[^Wd]w*>
         | ?'[^Wd]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.

压缩:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读