带if条件的正则表达式 [英] Regular expression with if condition

查看:56
本文介绍了带if条件的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是正则表达式的新手.我正在尝试构建一个正则表达式前三个字符必须是字母,然后字符串的其余部分可以是任何字符.如果前三个字符之后的字符串部分包含 &那么这部分应该以.

I am new to regular expression. I am trying to construct a regular expression that first three characters must be alphabets and then the rest of the string could be any character. If the part of the string after first three characters contains & then this part should start and end with ".

我能够构造 ^[a-z]{3} ,但卡在条件语句中.

I was able to construct ^[a-z]{3} , but stuck at conditional statement.

这可以在一个表达式中完成吗?

Can this be done in a single expression?

推荐答案

在大多数正则表达式风格中,您可以使用简单的前瞻来确保某些文本出现或不在当前位置右侧的某处,并使用交替运算符| 可以检查替代品.

In most regex flavors, you may use simple lookaheads to make sure some text is present or not somewhere to the right of the current locations, and using an alternation operator | it possible to check for alternatives.

所以,我们基本上有两种选择:在前 3 个字母之后的字符串中的某处有一个 & ,或者没有.因此,我们可以使用

So, we basically have 2 alternatives: there is a & somewhere in the string after the first 3 alphabets, or not. Thus, we can use

^[A-Za-z]{3}(?:(?=.*&)".*"|(?!.*&).*)$

查看正则表达式演示

详情:

  • ^ - 字符串的开始
  • [A-Za-z]{3} - 3 个字母
  • (?:(?=.*&)".*"|(?!.*&).*) - 两种选择之一:
    • (?=.*&)".*" - 如果字符串中的某处有 & ((?=.*&;)) 匹配 ",然后是任意 0+ 个字符,然后是 "
    • | - 或
    • (?!.*&).* - 如果没有 & ((?!.*&)) 在字符串中,只匹配任何 0+ 个字符直到...
    • ^ - start of string
    • [A-Za-z]{3} - 3 alphabets
    • (?:(?=.*&)".*"|(?!.*&).*) - Either of the two alternatives:
      • (?=.*&)".*" - if there is a & somewhere in the string ((?=.*&)) match ", then any 0+ characters, and then "
      • | - or
      • (?!.*&).* - if there is no & ((?!.*&)) in the string, just match any 0+ chars up to the...

      在 PCRE、.NET 或其他一些正则表达式中,您可以访问条件结构.这是一个 PCRE 演示:

      In PCRE, or .NET, or some other regex flavors, you have access to the conditional construct. Here is a PCRE demo:

      ^[A-Za-z]{3}(?(?=.*&)".*"|.*)$
                  ^^^^^^^^^^^^^^^^^
      

      (?(?=.*&)".*"|.*) 表示:

      • (?(?=.*&) - 如果任何 0+ 个字符后有 &...
      • ".*" - 匹配 "anything here"-like 字符串
      • | - 或者,如果没有 &
      • .* - 从当前位置(即前 3 个字母之后)匹配任意 0+ 个字符.
      • (?(?=.*&) - if there is a & after any 0+ characters...
      • ".*" - match "anything here"-like strings
      • | - or, if there is no &
      • .* - match any 0+ chars from the current position (i.e. after the first 3 alphabets).

      这篇关于带if条件的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆