Regular Expressions: Is there an AND operator?

后端 未结 12 2028
刺人心
刺人心 2020-11-21 06:34

Obviously, you can use the | (pipe?) to represent OR, but is there a way to represent AND as well?

Specifically, I\'d like to

相关标签:
12条回答
  • 2020-11-21 07:13

    The order is always implied in the structure of the regular expression. To accomplish what you want, you'll have to match the input string multiple times against different expressions.

    What you want to do is not possible with a single regexp.

    0 讨论(0)
  • 2020-11-21 07:15

    You could pipe your output to another regex. Using grep, you could do this:

    grep A | grep B

    0 讨论(0)
  • 2020-11-21 07:18

    Use AND outside the regular expression. In PHP lookahead operator did not not seem to work for me, instead I used this

    if( preg_match("/^.{3,}$/",$pass1) && !preg_match("/\s{1}/",$pass1))
        return true;
    else
        return false;
    

    The above regex will match if the password length is 3 characters or more and there are no spaces in the password.

    0 讨论(0)
  • Look at this example:

    We have 2 regexps A and B and we want to match both of them, so in pseudo-code it looks like this:

    pattern = "/A AND B/"
    

    It can be written without using the AND operator like this:

    pattern = "/NOT (NOT A OR NOT B)/"
    

    in PCRE:

    "/(^(^A|^B))/"
    
    regexp_match(pattern,data)
    
    0 讨论(0)
  • 2020-11-21 07:21

    Is it not possible in your case to do the AND on several matching results? in pseudocode

    regexp_match(pattern1, data) && regexp_match(pattern2, data) && ...
    
    0 讨论(0)
  • 2020-11-21 07:22

    Use a non-consuming regular expression.

    The typical (i.e. Perl/Java) notation is:

    (?=expr)

    This means "match expr but after that continue matching at the original match-point."

    You can do as many of these as you want, and this will be an "and." Example:

    (?=match this expression)(?=match this too)(?=oh, and this)

    You can even add capture groups inside the non-consuming expressions if you need to save some of the data therein.

    0 讨论(0)
提交回复
热议问题