개발! 딱 깔끔하고 센스있게!

논리적 연산자 및 php 정규 표현식 본문

개발 스크랩 메모/PHP

논리적 연산자 및 php 정규 표현식

렉사이 2020. 12. 21. 22:39

나는 정규 표현식에서 논리적 연산자'AND'를 사용하고 싶다.

내가 이거 해봤어:

(?=exp1)(?=exp2) 

근데 PHP 중에?= 작용이 없으니 PHP 언어 작성 프로그램이 필요하다.

또 다른 방법이 있나요?모든 조건과 어떤 순서가 존재한다면 표현식은 일치해야 한다.

나는 모든 배열상을 쓰고 싶지 않다:

(exp1)(exp2)(exp3)|(exp1)(exp3)(exp2)|.... 

대답

PHP 는 Lokahead 표현식을 확실히 지지합니다.

그러나 너는 그것들을 정확히 사용하지 않았을 것이다.

foo, bar, baz 3자의 문자열을 포함하려면 regex

^(?=.*foo)(?=.*bar)(?=.*baz) 

이 문자열 foobarbarbaz나 barbazfoo 등의 일치 항목을 되돌릴 것입니다.

하지만 이 일치 항목은 빈 문자열 (lookaheads 는 어떤 문자를 사용하지 않기 때문입니다.

만약 regex 문자열 자체로 되돌아가기를 희망한다면 사용하십시오

^(?=.*foo)(?=.*bar)(?=.*baz).* 

이 세 가지 조건을 충족한다면, 전체 문자열에 일치한다.

저는 그냥 쓰고 싶어요.

if (preg_match('/^(?=.*foo)(?=.*bar)(?=.*baz)/s', $subject)) { # Successful match } else { # Match attempt failed } 

이 또한 미식바 로켓과 같은 문자열을 맞추어 주십시오.만약 당신이 그러기 싫어한다면 (3개의 표현식 중 하나하나 모두 하나의 순수한 치환), 당신은 작은 테크닉으로 실현할 수 있습니다:

^(?:foo()|bar()|baz()){3}\1\2\3$ 

foobarbaz, foobazbar, barfoobaz, barbazfoo, bazfoobar, bazbarfoo'비결'의 영감은 Jan Goyvaerts, Seven Levithan 의 우수 저작'정규 표현식 식단'(304페이지)에서 비롯됐다.

그 작업 원리는 다음과 같다:

  • Each required part (foo etc.) is followed by an empty capturing group () which always matches if the required part has been matched.
  • So if all three required parts have matched, all three empty capturing groups have matched.
  • The following backreferences only succeed if each of the capturing groups has participated in the match.
  • So if the string is foobarbar, the part (?:foo()|bar()|baz()){3} will have matched, but \3 fails, so the overall regex fails.
  • If, however, all three did take part in the match, \1\2\3 succeeds in matching at the end of the string because each of the capturing groups contains nothing but the empty string.
Comments