繁体   English   中英

正则表达式匹配两个特定字符并获取第一个数字,然后是那些字符

[英]Regex Match two specific characters and get first numbers followed by those Characters

如果用户输入VX 是 20 m/s VY 是 40 m/s VZ 是 60 m/s

预期结果是来自输入的 Axis VX 和 20。

下面的代码也可以识别其他数字 40 和 60。

(VX)|(vx)|(Vx)|(vX)|[0-9]

利用

(?P<axis>vx)\s+\w+\s+(?P<value>\d+)

添加re.IGNORECASE 请参阅正则表达式证明

解释

 - Named Capture Group axis (?P<axis>vx)
   - vx matches the characters vx literally (case insensitive)
 - \s+ matches any whitespace characters between one and unlimited times, as many times as possible, giving back as needed (greedy)
 - \w+ matches any word characters between one and unlimited times, as many times as possible, giving back as needed (greedy)
 - \s+ matches any whitespace characters between one and unlimited times, as many times as possible, giving back as needed (greedy)
 - Named Capture Group value (?P<value>\d+)
   - \d+ matches a digits between one and unlimited times, as many times as possible, giving back as needed (greedy)

Python 代码演示

import re
text = r'VX is 20 m/s VY is 40 m/s  VZ is 60 m/s'
p = re.compile(r'(?P<axis>vx)\s+\w+\s+(?P<value>\d+)', re.IGNORECASE)
match = p.search(text)
if match:
    print(match.groupdict())

结果{'axis': 'VX', 'value': '20'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM