问题
I have a txt file containing strings as:
A 123
B 456
Ab(123)
......
I wish to search Ab(123)
in txt file.
What I have tried :
re.search(r'Ab(123)',string)
回答1:
There are 12 characters with special meanings, you escape to its literal meaning with \
in front of it.
re.search(r'Ab\(123\)',string)
# or re.findall(r'Ab\(123\)',string)
Look up https://regex101.com/r/1bb8oz/1 for detail.
回答2:
Ab\(123\)
In regex, there are 12 characters with special meanings: the backslash \
, the caret ^
, the dollar sign $
, the period or dot .
, the vertical bar or pipe symbol |
, the question mark ?
, the asterisk or star *
, the plus sign +
, the opening parenthesis (
, the closing parenthesis )
, the opening square bracket [
, and the opening curly brace {
, these special characters are often called metacharacters and should be escaped with backslash Ab\(123\)
if used as literal.
This can be automagically achieved using re.escape()
import re
string = "some text Ab(123) and more text"
if re.search(re.escape("Ab(123)"),string):
print("match")
- Regex Special Characters
- Python Demo
回答3:
Do you really need regex in the first place, if your goal is just to extract the lines where you have parentheses.
You could use the following approach:
input:
$ cat parentheses.txt
A 123
B 456
Ab(123)
uV(a5afgsg3)
A 123
output:
$ python parentheses.py
['Ab(123)', 'uV(a5afgsg3)']
code:
with open('parentheses.txt') as f:
content = f.readlines()
content = [x.strip() for x in content if '(' in x and ')' in x]
print(content)
If you really want to use regex:
import re
s = """
A 123
B 456
Ab(123)
uV(a5afgsg3)
A 123
"""
print(re.findall(r'^.*?\(.*?\).*$',s,re.MULTILINE))
output:
['Ab(123)', 'uV(a5afgsg3)']
demo: https://regex101.com/r/PGsguA/1
来源:https://stackoverflow.com/questions/57583748/how-to-search-a-string-with-parentheses-using-regular-expression