[英]Regular expression to extract numbers around a slash "/"
I tried to extract numbers in a format like "**/*,**/*"
.我试图以类似
"**/*,**/*"
的格式提取数字。
For example, for string "272/3,65/5"
, I want to get a list = [272,3,65,5]
例如,对于字符串
"272/3,65/5"
,我想得到一个list = [272,3,65,5]
I tried to use \\d*/
and /\\d*
to extract 272,65 and 3,5 separately, but I want to know if there's a method to get a list I showed above directly.我尝试使用
\\d*/
和/\\d*
分别提取 272,65 和 3,5,但我想知道是否有一种方法可以直接获取上面显示的列表。 Thanks!谢谢!
#importing regular expression module
import re
# input string
s = "272/3,65/5"
# with findall method we can extract text by given format
result = re.findall('\d+',s)
print(result) # ['272', '3', '65', '5']
['272', '3', '65', '5']
where the \\d means for matching digits in given input if we use \\d it gives output like below其中 \\d 表示匹配给定输入中的数字,如果我们使用 \\d 它会给出如下输出
result = re.findall('\d',s)
['2', '7', '2', '3', '6', '5', '5']
so we should use \\d+ where + matches in possible matches upto fail match所以我们应该在可能的匹配中使用 \\d+ where + 匹配到失败匹配
You can use [0-9]
to represent a single decimal digit.您可以使用
[0-9]
表示单个十进制数字。 so a better way of writing the regex would be something along the lines of [0-9]*/?[0-9]+,[0-9]+/?[0-9]*
.所以编写正则表达式的更好方法是
[0-9]*/?[0-9]+,[0-9]+/?[0-9]*
。 I'm assuming you are trying to match fractional points such as 5,2/3
, 23242/234,23
, or 0,0
.我假设您正在尝试匹配小数点,例如
5,2/3
、 23242/234,23
或0,0
。
Breakdown of the main components in [0-9]*/?[0-9]+,[0-9]+/?[0-9]*
: [0-9]*/?[0-9]+,[0-9]+/?[0-9]*
主要成分分解:
[0-9]*
matches 0 or more digits [0-9]*
匹配 0 个或多个数字/?
optionally matches a '/'
'/'
[0-9]+
matches at least one digit [0-9]+
至少匹配一位数字My favorite tool for debugging regexes is https://regex101.com/ since it explains what each of the operators means and shows you how the regex is preforming on a sample of your choice as you write it.我最喜欢的调试正则表达式的工具是https://regex101.com/,因为它解释了每个运算符的含义,并向您展示了正则表达式在您编写时如何在您选择的样本上执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.