【发布时间】:2018-01-20 15:05:38
【问题描述】:
在 Python 中,从 字符串 中取出两个特定 字符 之间包含的所有 字符 的快速方法是什么?
【问题讨论】:
-
你看过re module和正则表达式吗?
-
这是微不足道的。下次尝试更好地搜索...
-
你能告诉我们你期望的结果字符串吗?
-
@GalAbra 这行不通
在 Python 中,从 字符串 中取出两个特定 字符 之间包含的所有 字符 的快速方法是什么?
【问题讨论】:
您可以使用这个正则表达式:\(.*?\)。在这里演示:https://regexr.com/3jgmd
然后您可以使用此代码删除该部分:
import re
test_string = 'This is a string (here is a text to remove), and here is a text not to remove'
new_string = re.sub(r" \(.*?\)", "", test_string)
这个正则表达式 (regex) 将在括号中查找任何文本(不带换行符),括号中带有空格
【讨论】:
你很可能会使用像这样的正则表达式
\s*\([^()]*\)\s*
为此(请参阅a demo on regex101.com)。
该表达式会删除括号中的所有内容和周围的空格。
Python 中,这可能是:
import re
test_string = 'This is a string (here is a text to remove), and here is a text not to remove'
new_string = re.sub(r'\s*\([^()]*\)\s*', '', test_string)
print(new_string)
# This is a string, and here is a text not to remove
test_string = 'This is a string (here is a text to remove), and here is a text not to remove'
left = test_string.find('(')
right = test_string.find(')', left)
if left and right:
new_string = test_string[:left] + test_string[right+1:]
print(new_string)
# This is a string , and here is a text not to remove
后者的问题:它不考虑多次出现并且不删除空格,但它肯定更快。
0.578398942947 # regex solution
0.121736049652 # non-regex solution
【讨论】:
要删除 ( 和 ) 中的所有文本,您可以使用 re 中的 findall() 方法并使用 replace() 删除它们:
import re
test_string = 'This is a string (here is a text to remove), and here is a (second one) text not to remove'
remove = re.findall(r" \(.*?\)",test_string)
for r in remove:
test_string = test_string.replace(r,'')
print(test_string)
#result: This is a string , and here is a text not to remove
【讨论】: