正则表达式匹配两个特定字符并获取第一个数字,然后是那些字符
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
。参见 regex proof。
解释
- 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)
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'}
如果用户输入 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
。参见 regex proof。
解释
- 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)
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'}