简体   繁体   English

python正则表达式“12x4x67”只匹配第二组数字

[英]python regular expression "12x4x67" match only the second group of numbers

all i am a little stuck on this regular expression (Python beginner) I have a string here "12x4x67" and I need to split the numbers up into variables, for example: length, width and height.我对这个正则表达式有点卡住了(Python 初学者)我这里有一个字符串“12x4x67”,我需要将数字拆分为变量,例如:长度、宽度和高度。 I have successfully gotten the first group.我已经成功拿到了第一组。 Now I need to match the second group.现在我需要匹配第二组。 Here's a link to the regex tester I am using with the example I made.这是我在我制作的示例中使用的正则表达式测试器的链接。

Here is my regex :这是我的正则表达式

\d+

It only matches 340 in 340x9x20 .它只匹配340中的340x9x20

No regular expression needed:不需要正则表达式:

length, width, height = "12x4x67".split('x')

Or if you prefer dealing with integers:或者,如果您更喜欢处理整数:

length, width, height = [int(s) for s in "12x4x67".split('x')]

If your input always has all 3 parts - length, width and height - you can use如果您的输入始终包含所有 3 个部分 - 长度、宽度和高度 - 您可以使用

(?P<length>\d+)x(?P<width>\d+)x(?P<height>\d+)

See regex demo正则表达式演示

With named captures, you will be able to access any of the parts via a named group.使用命名捕获,您将能够通过命名组访问任何部分。

Python sample code : Python示例代码

import re
p = re.compile(r'(?P<length>\d+)x(?P<width>\d+)x(?P<height>\d+)')
s = "340x9x20"
m = p.search(s)
if (m):
    print(m.groupdict())
    # => {'length': '340', 'width': '9', 'height': '20'}
    print({k:int(v) for k,v in m.groupdict().items()})
    # => {'length': 340, 'width': 9, 'height': 20}

I would prefer the split approach, but to answer your question about regexps - this will use \\d+ to find ALL occurences:我更喜欢拆分方法,但要回答有关正则表达式的问题 - 这将使用\\d+来查找所有出现的情况:

lwh = "340x9x20"
numbers = [int(n) for n in re.findall("\d+", lwh)]
print(numbers)       # [340,9,20]

this can be optimized by using a pre-compiled regexp.这可以通过使用预编译的正则表达式进行优化。

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

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