-5

这些是 2 个样本:

Size: 15x6.5
Size: 15x7

我需要一个正则表达式命令来捕获“x”之前的数字,并需要另一个正则表达式命令来捕获之后的数字。

我想获得这样的东西:

Size: 15x6.5 --> 1) 15 2) 6.5
Size: 15x7   --> 1) 15 2) 7
4

1 回答 1

2

使用正则表达式:(\d+(?:\.\d+)?)x(\d+(?:\.\d+)?)

您没有指定您正在使用的正则表达式引擎。

Python

>>> import re
>>> matched = re.search(r'(\d+(?:\.\d+)?)x(\d+(?:\.\d+)?)', 'Size: 15x6.5')
>>> matched.groups()
('15', '6.5')
>>> matched = re.search(r'(\d+(?:\.\d+)?)x(\d+(?:\.\d+)?)', 'Size: 15x7')
>>> matched.groups()
('15', '7')

红宝石

>> 'Size: 15x6.5'.scan(/(\d+(?:\.\d+)?)x(\d+(?:\.\d+)?)/)
=> [["15", "6.5"]]
>> 'Size: 15x7'.scan(/(\d+(?:\.\d+)?)x(\d+(?:\.\d+)?)/)
=> [["15", "7"]]

Javascript

> 'Size: 15x6.5'.match(/(\d+(?:\.\d+)?)x(\d+(?:\.\d+)?)/)
["15x6.5", "15", "6.5"]
> 'Size: 15x7'.match(/(\d+(?:\.\d+)?)x(\d+(?:\.\d+)?)/)
["15x7", "15", "7"]

更新

使用(\d+(?:\.\d+)?)(?=x)(?<=x)(\d+(?:\.\d+)?)

于 2013-08-14T08:06:50.657 回答