[英]Python regex find single digit if no digits before it
I have a list of strings and I want to use regex to get a single digit if there are no digits before it.我有一个字符串列表,如果前面没有数字,我想使用正则表达式来获取单个数字。
strings = ['5.8 GHz', '5 GHz']
for s in strings:
print(re.findall(r'\d\s[GM]?Hz', s))
# output
['8 GHz']
['5 GHz']
# desired output
['5 GHz']
I want it to just return '5 GHz', the first string shouldn't have any matches.我希望它只返回“5 GHz”,第一个字符串不应该有任何匹配。 How can I modify my pattern to get the desired output?
如何修改我的模式以获得所需的 output?
>>> strings = ['5.8 GHz', '5 GHz']
>>>
>>> for s in strings:
... match = re.match(r'^[^0-9]*([0-9] [GM]Hz)', s)
... if match:
... print(match.group(1))
...
5 GHz
As per my comment, it seems that you can use:根据我的评论,您似乎可以使用:
(?<!\d\.)\d+\s[GM]?Hz\b
This matches:这匹配:
(?<.\d\.)
- A negative lookbehind to assert position is not right after any single digit and literal dot. (?<.\d\.)
- 在任何单个数字和文字点之后,断言 position 的否定回溯都不正确。\d+
- 1+ numbers matching the integer part of the frequency. \d+
- 1+ 个数字与频率的 integer 部分匹配。[GM]?Hz
- An optional uppercase G or M followed by "Hz". [GM]?Hz
- 可选的大写 G 或 M,后跟“Hz”。\b
- A word boundary. \b
- 单词边界。Updated Answer更新的答案
import re
a = ['5.8 GHz', '5 GHz', '8 GHz', '1.2', '1.2 Some Random String', '1 Some String', '1 MHz of frequency', '2 Some String in Between MHz']
res = []
for fr in a:
if re.match('^[0-9](?=.[^0-9])(\s)[GM]Hz$', fr):
res.append(fr)
print(res)
Output: ['5 GHz', '8 GHz']
Output:
['5 GHz', '8 GHz']
My two cents:我的两分钱:
selected_strings = list(filter(
lambda x: re.findall(r'(?:^|\s+)\d+\s+(?:G|M)Hz', x),
strings
))
With ['2 GHz', '5.8 GHz', ' 5 GHz', '3.4 MHz', '3 MHz', '1 MHz of Frequency']
as strings
, here selected_strings
:使用
['2 GHz', '5.8 GHz', ' 5 GHz', '3.4 MHz', '3 MHz', '1 MHz of Frequency']
作为strings
,这里selected_strings
:
['2 GHz', ' 5 GHz', '3 MHz', '1 MHz of Frequency']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.