[英]Regular expression to return text between parenthesis
u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'
我需要的只是括號內的內容。
如果你的問題真的就這么簡單,你就不需要正則表達式:
s[s.find("(")+1:s.find(")")]
使用re.search(r'\\((.*?)\\)',s).group(1)
:
>>> import re
>>> s = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'
>>> re.search(r'\((.*?)\)',s).group(1)
u"date='2/xc2/xb2',time='/case/test.png'"
如果要查找所有出現的情況:
>>> re.findall('\(.*?\)',s)
[u"(date='2/xc2/xb2',time='/case/test.png')", u'(eee)']
>>> re.findall('\((.*?)\)',s)
[u"date='2/xc2/xb2',time='/case/test.png'", u'eee']
基於 tkerwin 的答案,如果您碰巧有嵌套括號,例如
st = "sum((a+b)/(c+d))"
如果您需要在第一個左括號和最后(a+b)/(c+d)
右括號之間取出所有內容來獲取(a+b)/(c+d)
,那么他的答案將不起作用,因為 find 從字符串的左側開始搜索,並且會停在第一個右括號。
為了解決這個問題,你需要在操作的第二部分使用rfind
,所以它會變成
st[st.find("(")+1:st.rfind(")")]
import re
fancy = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'
print re.compile( "\((.*)\)" ).search( fancy ).group( 1 )
contents_re = re.match(r'[^\(]*\((?P<contents>[^\(]+)\)', data)
if contents_re:
print(contents_re.groupdict()['contents'])
無需使用正則表達式......只需使用列表切片......
string="(tidtkdgkxkxlgxlhxl) ¥£%#_¥#_¥#_¥#"
print(string[string.find("(")+1:string.find(")")])
以下是使用匹配的\\(([^()]+)\\)
正則表達式(請參閱其在線演示)在 Pandas 中提取括號之間的字符串的幾種方法
\\(
- a (
字符([^()]+)
- 然后將(
和)
以外的任何一個或多個字符捕獲到組 1 中\\)
- a )
字符。 使用Series.str.extract
提取第一次出現:
import pandas as pd
df = pd.DataFrame({'Description':['some text (value 1) and (value 2)']})
df['Values'] = df['Description'].str.extract(r'\(([^()]+)\)')
# => df['Values']
# 0 value 1
# Name: Values, dtype: object
使用Series.str.findall
提取(查找)所有匹配Series.str.findall
:
import pandas as pd
df = pd.DataFrame({'Description':['some text (value 1) and (value 2)']})
df['Values'] = df['Description'].str.findall(r'\(([^()]+)\)')
# => df['Values']
# 0 [value 1, value 2]
# Name: Values, dtype: object
df['Values'] = df['Description'].str.findall(r'\(([^()]+)\)').str.join(', ')
# => df['Values']
# 0 value 1, value 2
# Name: Values, dtype: object
請注意, .str.join(', ')
用於從結果字符串列表中創建一個逗號分隔的字符串。 您可以根據您的情況調整此分隔符。
TheSoulkiller的回答很棒。 就我而言,我需要處理額外的括號,並且只提取括號內的單詞。 一個很小的改變就可以解決問題
>>> s=u'abcde((((a+b))))-((a*b))'
>>> re.findall('\((.*?)\)',s)
['(((a+b', '(a*b']
>>> re.findall('\(+(.*?)\)',s)
['a+b', 'a*b']
測試用例
s = "(rein<unint>(pBuf) +fsizeof(LOG_RECH))"
結果
['pBuf', 'LOG_RECH', 'rein<unint>(pBuf) +fsizeof(LOG_RECH)']
實施
def getParenthesesList(s):
res = list()
left = list()
for i in range(len(s)):
if s[i] == '(':
left.append(i)
if s[i] == ')':
le = left.pop()
res.append(s[le + 1:i])
print(res)
return res
如果我沒有遺漏什么,對@tkerwin 的一個小修復:s[s.find("(")+1:s.rfind(")")]
第二個查找應該是 rfind 所以你從字符串末尾開始搜索
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.