正则匹配两个特定字符,并获得第一个数字,然后是这些字符

发布于 2025-01-20 15:32:25 字数 216 浏览 0 评论 0原文

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

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

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

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

If user inputs VX is 20 m/s VY is 40 m/s VZ is 60 m/s.

Expected results are the Axis VX and 20 from the input.

The code below also recognizes the other numbers 40 & 60 also.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

和影子一齐双人舞 2025-01-27 15:32:25

使用

(?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'}

Use

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

Add re.IGNORECASE. See regex proof.

EXPLANATION

 - 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 code demo:

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())

Results: {'axis': 'VX', 'value': '20'}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文