【问题标题】:Match a substring from last ":" of a match string匹配匹配字符串的最后一个“:”的子字符串
【发布时间】:2020-12-02 13:55:10
【问题描述】:

我想从与此模式匹配的字符串中获取子字符串:

:((?![{\[\-\d])([^,}]+))

match all string value.

例如:

altitude{altitudeValue:52420,altitudeConfidence:alt-002-00}}},
highFrequencyContainer:basicVehicleContainerHighFrequency:
{heading{headingValue:3601,headingConfidence:127},speed{speedValue:0,speedConfidence:127},
driveDirection:unavailable

我与此字符串上方的模式匹配:

:alt-002-00
:basicVehicleContainerHighFrequency:{heading{headingValue:3601
:unavailable

但我想要:

:alt-002-00
NO: **:3601**  <--match from last ":" to end of previous match (is possible with regex?) only if is a 
string.
YES: if was **:hello** <-match because is a string
:unavailable

我想从最后一个“:”匹配到上一个匹配的结尾(可以使用正则表达式吗?)。 如何改变我的模式规则? :((?![{\[\-\d])([^,}]+))

谢谢 问候

【问题讨论】:

  • 如果冒号后面包含字母字符,你想匹配它吗(从技术上讲,'3601' 在这种情况下是一个字符串)?
  • 是最后一个“:”之后的字符串
  • @Catanzaro 有没有解决方案?

标签: regex substring


【解决方案1】:

如果您将正则表达式中的([^,}]+) 替换为:(?:(?:(?!:\d)[^,}])+),则它不会扫描冒号后跟数字:

import re

s = """altitude{altitudeValue:52420,altitudeConfidence:alt-002-00}}},
highFrequencyContainer:basicVehicleContainerHighFrequency:
{heading{headingValue:3601,headingConfidence:127},speed{speedValue:0,speedConfidence:127},
driveDirection:unavailable"""

re.findall(r'(?::(?![{\[\-\d])(?:(?:(?!:\d)[^,}])+))', s)

打印:

[':alt-002-00',
 ':basicVehicleContainerHighFrequency:\n{heading{headingValue',
 ':unavailable']

Regex Demo

请注意,上述正则表达式中没有捕获组(0 除外)。

【讨论】:

  • 我不想要 :basicVehicleContainerHighFrequency:\n{heading{headingValue
  • 除了说你不想要它之外,这个字符串还能消除什么?
【解决方案2】:

可以通过将: 添加到否定字符类来匹配最后一个:。要获得子匹配,您可以使用单个捕获组而不是 2 个。

:((?![{\[\d-])[^:,}]+)

说明

  • :Match 字面意思
  • (捕获组1
    • (?![{\[\d-]) 负前瞻,断言右边不是{ [ 一个数字或-
    • [^:,}]+ 匹配除 @987654332 以外的任何字符 1 次以上@ , }
  • )关闭第一组

Regex demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    • 2018-10-27
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多