How to search a string with parentheses using regular expression? [duplicate]

こ雲淡風輕ζ 提交于 2021-02-10 05:44:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!