정규식 내에서 변수를 사용하는 방법은 무엇입니까?
variable
내부 를 사용하고 싶습니다 regex
. 어떻게 할 수 Python
있습니까?
TEXTO = sys.argv[1]
if re.search(r"\b(?=\w)TEXTO\b(?!\w)", subject, re.IGNORECASE):
# Successful match
else:
# Match attempt failed
정규식을 문자열로 작성해야합니다.
TEXTO = sys.argv[1]
my_regex = r"\b(?=\w)" + re.escape(TEXTO) + r"\b(?!\w)"
if re.search(my_regex, subject, re.IGNORECASE):
etc.
사용 주 re.escape
텍스트에 특수 문자가 포함되어 있으면, 그들은 이와 같이 해석되지 않도록합니다.
if re.search(r"\b(?<=\w)%s\b(?!\w)" % TEXTO, subject, re.IGNORECASE):
이것은 TEXTO에있는 것을 정규식에 문자열로 삽입합니다.
rx = r'\b(?<=\w){0}\b(?!\w)'.format(TEXTO)
여러 개의 작은 패턴을 함께 묶어 정규 표현식 패턴을 작성하는 것이 매우 편리하다는 것을 알았습니다.
import re
string = "begin:id1:tag:middl:id2:tag:id3:end"
re_str1 = r'(?<=(\S{5})):'
re_str2 = r'(id\d+):(?=tag:)'
re_pattern = re.compile(re_str1 + re_str2)
match = re_pattern.findall(string)
print(match)
산출:
[('begin', 'id1'), ('middl', 'id2')]
python 3.6부터는 Literal String Interpolation , "f-strings"를 사용할 수 있습니다 . 특별한 경우 해결책은 다음과 같습니다.
if re.search(rf"\b(?=\w){TEXTO}\b(?!\w)", subject, re.IGNORECASE):
...do something
다음을 제외하고 위의 모든 사항에 동의합니다.
sys.argv[1]
같은 것 Chicken\d{2}-\d{2}An\s*important\s*anchor
sys.argv[1] = "Chicken\d{2}-\d{2}An\s*important\s*anchor"
이 re.escape
경우 정규 표현식처럼 동작하기를 원하기 때문에을 사용하고 싶지 않습니다.
TEXTO = sys.argv[1]
if re.search(r"\b(?<=\w)" + TEXTO + "\b(?!\w)", subject, re.IGNORECASE):
# Successful match
else:
# Match attempt failed
서로 비슷한 사용자 이름을 검색해야했으며 Ned Batchelder가 말한 내용이 매우 유용했습니다. 그러나 re.compile을 사용하여 다시 검색 용어를 만들 때 더 깨끗한 출력을 얻었습니다.
pattern = re.compile(r"("+username+".*):(.*?):(.*?):(.*?):(.*)"
matches = re.findall(pattern, lines)
다음을 사용하여 출력을 인쇄 할 수 있습니다.
print(matches[1]) # prints one whole matching line (in this case, the first line)
print(matches[1][3]) # prints the fourth character group (established with the parentheses in the regex statement) of the first line.
format
grammer suger를 사용하여 다른 사용법을 시도 할 수 있습니다 .
re_genre = r'{}'.format(your_variable)
regex_pattern = re.compile(re_genre)
format 키워드도 사용할 수 있습니다. Format 메서드는 {} 자리 표시자를 인수로 format 메서드에 전달한 변수로 바꿉니다.
if re.search(r"\b(?=\w)**{}**\b(?!\w)".**format(TEXTO)**, subject, re.IGNORECASE):
# Successful match**strong text**
else:
# Match attempt failed
참고 URL : https://stackoverflow.com/questions/6930982/how-to-use-a-variable-inside-a-regular-expression
'Programing' 카테고리의 다른 글
백 슬래시로 쉘 명령을 시작하는 이유는 무엇입니까? (0) | 2020.05.12 |
---|---|
PHP의 비동기 셸 실행 (0) | 2020.05.12 |
Node.js REPL에서) (을 사용하여 함수를 호출하는 이유는 무엇입니까? (0) | 2020.05.12 |
Git 브랜치 이름에 슬래시 문자 사용 (0) | 2020.05.12 |
HTML 인코딩 문제-“”대신“”문자가 나타남 (0) | 2020.05.12 |