수색…


통사론

  • 정규식? 스위치? exp 문자열? matchVar? ? subMatchVar subMatchVar ...?
  • regsub? 스위치? exp string subSpec? varName?

비고

이 주제는 정규 표현식 자체를 논의하기위한 것이 아닙니다. 정규 표현식을 만드는 데 도움이되는 정규 표현식과 도구를 설명하는 인터넷상의 자료가 많이 있습니다.

이 항목에서는 Tcl에서 정규 표현식을 사용하는 일반적인 스위치와 방법 및 Tcl과 다른 정규 표현 엔진 간의 차이점에 대해 설명합니다.

정규식은 일반적으로 느립니다. 당신이 묻어야 할 첫 번째 질문은 "나는 정말로 정규 표현식이 필요한가요?"입니다. 당신이 원하는 대로만 일치하십시오. 다른 데이터가 필요하지 않은 경우 일치시키지 마십시오.

이러한 정규 표현식 예제의 목적을 위해 정규 표현식을 설명하고 설명 할 수 있도록 확장 된 스위치가 사용됩니다.

어울리는

regexp 명령은 정규 표현식을 문자열과 비교하는 데 사용됩니다.

# This is a very simplistic e-mail matcher.
# e-mail addresses are extremely complicated to match properly.
# there is no guarantee that this regex will properly match e-mail addresses.
set mydata "send mail to [email protected] please"
regexp -expanded {
    \y           # word boundary
    [^@\s]+      # characters that are not an @ or a space character
    @            # a single @ sign
    [\w.-]+      # normal characters and dots and dash
    \.           # a dot character
    \w+          # normal characters.
    \y           # word boundary
    } $mydata emailaddr
puts $emailaddr
[email protected]

regexp 명령은 일치하는 경우 1 (참) 값을 반환하고 일치하지 않으면 0 (거짓)을 반환합니다.

set mydata "hello wrld, this is Tcl"
# faster would be to use: [string match *world* $mydata] 
if { [regexp {world} $mydata] } {
   puts "spelling correct"
} else {
   puts "typographical error"
}

일부 데이터의 모든 표현식을 일치 시키려면, -all 스위치와 -inline 스위치를 사용하여 데이터를 리턴하십시오. 기본값은 다른 데이터와 마찬가지로 개행을 처리하는 것입니다.

# simplistic english ordinal word matcher.
set mydata {
    This is the first line.
    This is the second line.
    This is the third line.
    This is the fourth line.
    }
set mymatches [regexp -all -inline -expanded {
    \y                  # word boundary
    \w+                 # standard characters
    (?:st|nd|rd|th)     # ending in st, nd, rd or th
                        # The ?: operator is used here as we don't
                        # want to return the match specified inside
                        # the grouping () operator.
    \y                  # word boundary
    } $mydata]
puts $mymatches
first second third fourth
# if the ?: operator was not used, the data returned would be:
first st second nd third rd fourth th

뉴 라인 처리

# find real numbers at the end of a line (fake data).
set mydata {
    White 0.87 percent saturation.
    Specular reflection: 0.995
    Blue 0.56 percent saturation.
    Specular reflection: 0.421
    }
# the -line switch will enable newline matching.
# without -line, the $ would match the end of the data.
set mymatches [regexp -line -all -inline -expanded {
    \y                  # word boundary
    \d\.\d+             # a real number
    $                   # at the end of a line.
    } $mydata]
puts $mymatches
0.995 0.421

유니 코드는 특별한 처리가 필요하지 않습니다.

% set mydata {123ÂÃÄÈ456}
123ÂÃÄÈ456
% regexp {[[:alpha:]]+} $mydata match
1
% puts $match
ÂÃÄÈ
% regexp {\w+} $mydata match
1
% puts $match
123ÂÃÄÈ456

문서 : regexp re_syntax

욕심쟁이 및 비 욕심 많은 한정어 혼합하기

첫 번째 한정 기호와 같이 욕심이 일치하는 경우 전체 RE는 욕심이 많습니다.

첫 번째 한정 기호와 일치하지 않는 항목이 있으면 전체 RE는 욕심이 없습니다.

set mydata {
    Device widget1: port: 156 alias: input2
    Device widget2: alias: input1 
    Device widget3: port: 238 alias: processor2
    Device widget4: alias: output2
    }
regexp {Device\s(\w+):\s(.*?)alias} $mydata alldata devname devdata
puts "$devname $devdata"
widget1 port: 156 alias: input2
regexp {Device\s(.*?):\s(.*?)alias} $mydata alldata devname devdata
puts "$devname $devdata" 
widget1 port: 156 

첫 번째 경우 첫 번째 \ w +는 욕심이 많으므로 모든 한정 기호는 greedy 및. *로 표시됩니다. 예상보다 많은 성냥.

두 번째 경우에는 첫 번째. *? 비 탐욕적이고 모든 한정어는 비 탐욕심으로 표시됩니다.

다른 정규식 엔진은 greedy / non-greedy 한정 기호에 문제가 없지만 훨씬 느립니다.

헨리 스펜서는 썼다 : ... 말썽이 혼합 - 탐욕 정규 표현식을 포함하는 문장의 일반화 작성하는 매우 어려운 것입니다 - 혼합 탐욕 정규 표현식이 일치해야하는지의 적절한 구현에 독립적 인 정의를 - - 그들이 "사람들이 기대하는 것"을하도록합니다. 난 노력 했어. 나는 아직도 노력하고있어. 지금까지 행운이 없습니다. ...

치환

regsub 명령은 정규식 일치 및 대체에 사용됩니다.

set mydata {The yellow dog has the blues.}
# create a new string; only the first match is replaced.
set newdata [regsub {(yellow|blue)} $mydata green]
puts $newdata
The green dog has the blues.
# replace the data in the same string; all matches are replaced
regsub -all {(yellow|blue)} $mydata red mydata
puts $mydata
The red dog has the reds.
# another way to create a new string
regsub {(yellow|blue)} $mydata red mynewdata
puts $mynewdata
The red dog has the blues.

일치하는 데이터를 참조하기 위해 역 참조를 사용합니다.

set mydata {The yellow dog has the blues.}
regsub {(yellow)} $mydata {"\1"} mydata
puts $mydata
The "yellow" dog has the blues.

문서 : regsub re_syntax

Tcl의 RE 엔진과 다른 RE 엔진 간의 차이점.

  • \ m : 단어의 시작.
  • \ M : 단어의 끝.
  • \ y : 단어 경계.
  • \ Y : 단어 경계가 아닌 점.
  • \ Z : 데이터의 끝과 일치합니다.

문서 : re_syntax

리터럴 문자열과 정규 표현식의 일치

때로는 리터럴 (하위) 문자열을 RE 메타 문자가 포함 된 부분 문자열에도 불구하고 정규 표현식과 일치시켜야 할 때가 있습니다. 예, 적절한 백 슬래시를 삽입하여 ( string map 사용하여) 해당 백 슬래시를 삽입하는 코드를 작성하는 것이 가능합니다. ***= 패턴 앞에 접두어를 붙이는 것이 가장 쉽습니다. RE 엔진이 나머지 문자열을 단지 문자 그대로 취급합니다 모든 추가 메타 문자를 비활성화 합니다 .

set sampleText "This is some text with \[brackets\] in it."
set searchFor {[brackets]}

if {[ regexp ***=$searchFor $sampleText ]} {
    # This message will be printed
    puts "Found it!"
}

이것은 또한 앵커를 사용할 수 없다는 것을 의미합니다.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow