简体   繁体   中英

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

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]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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