python - python 3 中的 List 中的特定模式字符串

标签 python regex

要求:使用正则表达式希望仅获取特定字符串,即输入列表中“-”和“*”符号之间的字符串。下面是代码片段

    ZTon = ['one-- and preferably only one --obvious', " Hello World", 'Now is better than never.', 'Although never is often better than *right* now.']
ZTon = [ line.strip() for line in ZTon]
print (ZTon)
r = re.compile(".^--")
portion = list(filter(r.match, ZTon)) # Read Note
print (portion)

预期响应:

['and preferably only one','right']

最佳答案

使用正则表达式

import re
ZTon = ['one-- and preferably only one --obvious', " Hello World", 'Now is better than never.', 'Although never is often better than *right* now.']
pattern=r'(--|\*)(.*)\1'
l=[]
for line in ZTon:
    s=re.search(pattern,line)
    if s:l.append(s.group(2).strip())
print (l)
# ['and preferably only one', 'right']

关于python - python 3 中的 List 中的特定模式字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56528228/

相关文章:

python - Python 异常(除了 SyntaxError 之外)是运行时错误吗?

regex - 如何删除除数字和给定列表之外的所有单词?

python - Pandas 删除字符串中的部分空格

c# - 使用正则表达式将字符串拆分成句子

regex - 这个 perl 正则表达式有什么问题?

java - 正则表达式在 Ruby 中匹配,但在 Java 中不匹配?

python - 我的 python 代码有什么错误?

python - 运行 pylint 返回 ModuleNotFoundError : No module named 'wrapt.wrappers'

Python检查文件状态是否正在上传

python - 在Linux上麦克风静音时如何收听?