【问题标题】:Python regex to extract words (ended with specific non-duplicated letter) in sentence [duplicate]Python正则表达式提取句子中的单词(以特定的非重复字母结尾)
【发布时间】:2023-01-25 15:14:52
【问题描述】:

我想提取“xxm”部分的字符串。

我在下面尝试过:

ss = ['The stick is 36mm wide 20m long white', 
'Another is 55mm wide 10m long black', 
'Last one the length is 360m']

for s in ss:
    found = re.findall(r' [0-9]+m', s)
    print (found)

想要的结果分别是“20m”和“10m”,但它输出:

[' 36m', ' 20m']
[' 55m', ' 10m']

我试图将其更改为以下,但这不是解决方案。

r' [0-9]+m$'

如何提取仅以 1 'm'(不是 'mm')结尾的部分?谢谢你。

【问题讨论】:

  • 为什么不直接在正则表达式字符串的末尾添加一个空格? $ 基本上意味着您匹配的内容必须在行尾。
  • @someguy,谢谢你的评论!可能需要的部分在字符串末尾。

标签: python regex


【解决方案1】:

这是一个可能的解决方案(使用 作为单词边界):

found = re.findall(r'[0-9]+m', s)

输出:

['20m']
['10m']
['360m']

【讨论】:

    猜你喜欢
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    相关资源
    最近更新 更多