簡體   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