您甚至不需要使用regex,最有效的方法是将字符串拆分为单词,然后检查它是否以下划线开头和结尾。
def get_underscored(text):
for word in text.split():
if word.startswith("_") and word.endswith("_"):
yield word
test = ['abc text_ abc',
'abc _text abc,',
'abc text_textUnderscored abc',
'abc :_text abc',
'abc _text_ abc',
'abc __text__ abc']
test_str = ' '.join(test)
print(list(get_underscored(test_str)))
结果是
['_text_', '__text__']
.
尽管这种方法在较大的输入上的伸缩性不如regex,但在较小的输入上的伸缩性要快几个数量级。