전제 조건: 예제가 포함된 정규 표현식 | 파이썬
정규식(때때로 유리식이라고도 함)은 검색 패턴을 정의하는 문자 시퀀스로, 주로 문자열과의 패턴 일치 또는 문자열 일치(예: 찾기 및 바꾸기 유사 작업)에 사용됩니다. 정규식은 패턴을 문자 시퀀스와 일치시키는 일반화된 방법입니다.
이진 트리 vs 이진 검색 트리
기준 치수 정규식(RE) 일치하는 문자열(패턴) 세트를 지정합니다. RE 비유를 이해하려면,MetaCharacters>유용하고 중요하며 모듈의 기능에 사용됩니다.re>.
총 14개의 메타 문자가 있으며 각 문자의 기능에 대해 설명합니다.
Used to drop the special meaning of character following it (discussed below) [] Represent a character class ^ Matches the beginning $ Matches the end . Matches any character except newline ? Matches zero or one occurrence. | Means OR (Matches with any of the characters separated by it. * Any number of occurrences (including 0 occurrences) + One or more occurrences {} Indicate number of occurrences of a preceding RE to match. () Enclose a group of REs> 연구()
re.search()>메소드는 None(패턴이 일치하지 않는 경우)을 반환하거나re.MatchObject>문자열의 일치하는 부분에 대한 정보가 포함되어 있습니다. 이 방법은 첫 번째 일치 후에 중지되므로 데이터 추출보다 정규식을 테스트하는 데 가장 적합합니다.
예:
파이썬3
# A Python program to demonstrate working of re.match().> import> re> > # Lets use a regular expression to match a date string> # in the form of Month name followed by day number> regex>=> r>'([a-zA-Z]+) (d+)'> > match>=> re.search(regex,>'I was born on June 24'>)> > if> match !>=> None>:> > ># We reach here when the expression '([a-zA-Z]+) (d+)'> ># matches the date string.> > ># This will print [14, 21), since it matches at index 14> ># and ends at 21.> >print>(>'Match at index % s, % s'> %> (match.start(), match.end()))> > ># We us group() method to get all the matches and> ># captured groups. The groups contain the matched values.> ># In particular:> ># match.group(0) always returns the fully matched string> ># match.group(1) match.group(2), ... return the capture> ># groups in order from left to right in the input string> ># match.group() is equivalent to match.group(0)> > ># So this will print 'June 24'> >print>(>'Full match: % s'> %> (match.group(>0>)))> > ># So this will print 'June'> >print>(>'Month: % s'> %> (match.group(>1>)))> > ># So this will print '24'> >print>(>'Day: % s'> %> (match.group(>2>)))> > else>:> >print>(>'The regex pattern does not match.'>)> |
>
>
산출:
Match at index 14, 21 Full match: June 24 Month: June Day: 24>
re.findall()
문자열의 패턴과 겹치지 않는 모든 일치 항목을 문자열 목록으로 반환합니다. 문자열은 왼쪽에서 오른쪽으로 스캔되며 일치하는 항목이 발견된 순서대로 반환됩니다.
예:
파이썬3
# A Python program to demonstrate working of> # findall()> import> re> > # A sample text string where regular expression> # is searched.> string>=> '''Hello my Number is 123456789 and> >my friend's number is 987654321'''> > # A sample regular expression to find digits.> regex>=> 'd+'> > match>=> re.findall(regex, string)> print>(match)> |
>
>
산출:
['123456789', '987654321']>