[英]python regex to display text in parenthesis
我進行了編碼以在內(“和內”)打印ext,但是我得到了錯誤。
我的意思是,如果我有文字: hello everyone("Can you see")
,那么它必須打印為Can you see
我的編碼:
>>> import re
>>> s = "<_io.TextIOWrapper ('C:/Python34/abcd.txt') mode='w' encoding='cp1252'>"
>>> m = re.search(r"(?<=\('\=\')[^\']*", s)
>>> m.group()
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
m.group()
AttributeError: 'NoneType' object has no attribute 'group'
稍微修改一下外觀:
(?<=\(')[^']*
您將得到以下結果:
>>> m = re.search( r"(?<=\(')[^']*", s)
>>> m.group()
'C:/Python34/abcd.txt'
為了能夠同時匹配'
和"
為你提的意見 ,你需要創建另一個捕獲組(用於回參考):
(?<=\((['"]))(.*?)\1
因此:
>>> m = re.search( r"(?<=\(([\"']))(.*?)\1", s)
>>> m.group()
"C:/Python34/abcd.txt'"
>>> m.group(1)
"'"
>>> m.group(2)
'C:/Python34/abcd.txt'
嘗試這樣的事情,它將使用單引號或雙引號。 group(1)
給出內部字符串。 此正則表達式轉義外部括號,因此它們不代表分組。
>>> m = re.search(r"\(['\"](.+)?['\"]\)", s)
>>> m.group(0)
"('C:/Python34/abcd.txt')"
>>> m.group(1)
'C:/Python34/abcd.txt'
>>> m.group(1)
試試這個簡單的正則表達式: ('.*?')
。 它對引號內的所有內容進行非貪婪搜索。
import re
s = "<_io.TextIOWrapper ('C:/Python34/abcd.txt') mode='w' encoding='cp1252'>"
regex = re.compile(r"('.*?')")
m = regex.search(s)
m.group()
它產生以下輸出:
"'C:/Python34/abcd.txt'"
您還可以使用re.VERBOSE
表達式和groupdict
:
import re
s = "<_io.TextIOWrapper ('C:/Python34/abcd.txt') mode='w' encoding='cp1252'>"
regex = re.compile(r"""
\(
(?P<quoted>'.*?')
\)
""", re.VERBOSE)
m = regex.search(s)
m.groupdict()["quoted"]
這個正則表達式可以做到:
m = re.search(r"(?<=\()[^\)]*", s)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.