Program Tip

정규식은 전체 단어 만 일치

programtip 2020. 10. 16. 07:59
반응형

정규식은 전체 단어 만 일치


데이터베이스에 저장된 용어집에 포함 된 대소 문자를 구분하지 않고 주어진 콘텐츠 블록에서 모든 단어를 찾는 데 사용하는 정규식이 있습니다. 내 패턴은 다음과 같습니다.

/($word)/i

문제는 내가 사용 하면 일치하는 /(Foo)/i것과 같은 단어를 사용 Food한다는 것입니다. 단어 양쪽에 공백 또는 단어 경계가 있어야합니다.

Foo문장의 시작, 중간 또는 끝에있는 단어 일 때 단어 만 일치하도록 내 표현을 수정하려면 어떻게 해야합니까?


단어 경계 사용 :

/\b($word)\b/i

또는 Sinan Ünür의 예에서와 같이 "SPECTRE"를 검색하는 경우 :

/(?:\W|^)(\Q$word\E)(?:\W|$)/i

전체 단어를 일치 시키려면 패턴을 사용합니다. (\w+)

PCRE 또는 이와 유사한 것을 사용한다고 가정합니다.

여기에 이미지 설명 입력

이 라이브 예제에서 가져온 위의 스크린 샷 : http://regex101.com/r/cU5lC2

명령 줄의 전체 단어를 (\w+)

Ubuntu 12.10 에서 phpsh 대화 형 셸사용하여 preg_match 라는 방법을 통해 PCRE 정규식 엔진 을 시연 할 것입니다.

phpsh를 시작하고 일부 내용을 변수에 넣고 단어와 일치시킵니다.

el@apollo:~/foo$ phpsh

php> $content1 = 'badger'
php> $content2 = '1234'
php> $content3 = '$%^&'

php> echo preg_match('(\w+)', $content1);
1

php> echo preg_match('(\w+)', $content2);
1

php> echo preg_match('(\w+)', $content3);
0

는 preg_match 방법 변수를 분석 PHP 언어 내의 PCRE 엔진을 사용했을 때 $content1, $content2$content3(\w)+패턴.

$ content1 및 $ content2에는 하나 이상의 단어가 포함되어 있지만 $ content3에는 포함되지 않습니다.

명령 줄에있는 여러 리터럴 단어를 (dart|fart)

el@apollo:~/foo$ phpsh

php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'farty gun';
php> $gun4 = 'unicorn gun';

php> echo preg_match('(dart|fart)', $gun1);
1

php> echo preg_match('(dart|fart)', $gun2);
1

php> echo preg_match('(dart|fart)', $gun3);
1

php> echo preg_match('(dart|fart)', $gun4);
0

변수 gun1 및 gun2에는 문자열 dart 또는 fart가 포함됩니다. gun4는 그렇지 않습니다. 그러나 fart일치 하는 단어를 찾는 것은 문제가 될 수 있습니다 farty. 이 문제를 해결하려면 정규식에서 단어 경계를 적용하십시오.

Match literal words on the commandline with word boundaries.

el@apollo:~/foo$ phpsh

php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'farty gun';
php> $gun4 = 'unicorn gun';

php> echo preg_match('(\bdart\b|\bfart\b)', $gun1);
1

php> echo preg_match('(\bdart\b|\bfart\b)', $gun2);
1

php> echo preg_match('(\bdart\b|\bfart\b)', $gun3);
0

php> echo preg_match('(\bdart\b|\bfart\b)', $gun4);
0

So it's the same as the previous example except that the word fart with a \b word boundary does not exist in the content: farty.


Using \b can yield surprising results. You would be better off figuring out what separates a word from its definition and incorporating that information into your pattern.

#!/usr/bin/perl

use strict; use warnings;

use re 'debug';

my $str = 'S.P.E.C.T.R.E. (Special Executive for Counter-intelligence,
Terrorism, Revenge and Extortion) is a fictional global terrorist
organisation';

my $word = 'S.P.E.C.T.R.E.';

if ( $str =~ /\b(\Q$word\E)\b/ ) {
    print $1, "\n";
}

Output:

Compiling REx "\b(S\.P\.E\.C\.T\.R\.E\.)\b"
Final program:
   1: BOUND (2)
   2: OPEN1 (4)
   4:   EXACT  (9)
   9: CLOSE1 (11)
  11: BOUND (12)
  12: END (0)
anchored "S.P.E.C.T.R.E." at 0 (checking anchored) stclass BOUND minlen 14
Guessing start of match in sv for REx "\b(S\.P\.E\.C\.T\.R\.E\.)\b" against "S.P
.E.C.T.R.E. (Special Executive for Counter-intelligence,"...
Found anchored substr "S.P.E.C.T.R.E." at offset 0...
start_shift: 0 check_at: 0 s: 0 endpos: 1
Does not contradict STCLASS...
Guessed: match at offset 0
Matching REx "\b(S\.P\.E\.C\.T\.R\.E\.)\b" against "S.P.E.C.T.R.E. (Special Exec
utive for Counter-intelligence,"...
   0           |  1:BOUND(2)
   0           |  2:OPEN1(4)
   0           |  4:EXACT (9)
  14      |  9:CLOSE1(11)
  14      | 11:BOUND(12)
                                  failed...
Match failed
Freeing REx: "\b(S\.P\.E\.C\.T\.R\.E\.)\b"

use word boundaries \b,

The following (using four escapes) works in my environment: Mac, safari Version 10.0.3 (12602.4.8)

var myReg = new RegExp(‘\\\\b’+ variable + ‘\\\\b’, ‘g’)

If you are doing it in Notepad++

[\w]+ 

전체 단어를 제공하고 괄호를 추가하여 그룹으로 가져올 수 있습니다. 예 : conv1 = Conv2D(64, (3, 3), activation=LeakyReLU(alpha=a), padding='valid', kernel_initializer='he_normal')(inputs). LeakyReLU주석으로 자신의 줄로 이동 하고 현재 활성화를 대체하고 싶습니다 . 메모장 ++에서는 다음 찾기 명령을 사용하여 수행 할 수 있습니다.

([\w]+)( = .+)(LeakyReLU.alpha=a.)(.+)

교체 명령은 다음과 같습니다.

\1\2'relu'\4 \n    # \1 = LeakyReLU\(alpha=a\)\(\1\)

공백은 내 코드에서 올바른 형식을 유지하는 것입니다. :)

참고 URL : https://stackoverflow.com/questions/1751301/regex-match-entire-words-only

반응형