python - 通过正则表达式在 python 中过滤以某些字符(所有出现)结尾的文本

标签 python regex text filtering

我正在尝试在 python 中过滤文本

import re
text = "Fast charging 25W, USB Power Delivery 3.0, Fast Qi/PMA wireless charging 12W, Reverse wireless charging 4.5W"
regex = re.compile("\w+\s\w+harg\w+\s\d+W")  
mc = regex.findall(text)
print(mc)

结果是

['Fast charging 25W', 'wireless charging 12W']

但是,我想做的是让所有事件都以 *W"结尾

['Fast charging 125W', 'Fast Qi/PMA wireless charging 12W', 'Reverse wireless charging 4.5W']

数量可以大很多(比如Charge 1250W) 我在谷歌上搜索了将近 2 个小时,搜索了很多关于正则表达式的文档,但没有成功。任何帮助将不胜感激。

谢谢。

最佳答案

您正在寻找单词边界,如果我理解正确的话,逗号之间的所有内容:

[^,]+?W\b
  • 所有不是逗号的东西,懒惰
  • 文字大写 W,后跟单词边界 \b

Online Demo , 代码示例:

import re
regex = r"[^,]+?W\b"
test_str = ("text = \"Fast charging 25W, USB Power Delivery 3.0, Fast Qi/PMA wireless charging 12W, Reverse wireless charging 4.5W\"\n")
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):  
    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

关于python - 通过正则表达式在 python 中过滤以某些字符(所有出现)结尾的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65077422/

相关文章:

python - Docker获取用户真实ip

python - 使用多个定界符拆分字符串

android - 水平翻转 TextView

java - 如何拆分文本文件并在一行中存储 2 个值?

python - 注意层抛出 TypeError : Permute layer does not support masking in Keras

python - django 如何从子关系中获取字段到父模板中

python根据条件替换单词

regex - 什么是正确的 VIM 正则表达式来搜索以获得 = 而不是 ==?

regex - 如何在 Visual Studio Code 中替换文档中的每一个换行符,而不是每两个换行符(或更多)?

ios - 如果我想要格式化文本但不想使用 UIWebView,那么 Core Text 是我唯一剩下的选择吗?