[英]Write a Regex to extract number before '/'
I don't want to use string split because I have numbers 1-99, and a column of string that contain '#/#' somewhere in the text. 我不想使用字符串拆分,因为我有数字1-99,并且在文本中某处包含'#/#'的字符串列。
How can I write a regex to extract the number 10 in the following example: 在以下示例中,如何编写正则表达式来提取数字10:
He got 10/19 questions right.
Use a lookahead to match on the /
, like this: 先行匹配
/
,如下所示:
\d+(?=/)
You may need to escape the / if your implementation uses it as its delimiter. 如果您的实现使用/作为分隔符,则可能需要转义。
Live example: https://regex101.com/r/xdT4vq/1 实时示例: https : //regex101.com/r/xdT4vq/1
You can still use str.split()
if you carefully construct logic around it: 如果您仔细构造
str.split()
逻辑,仍可以使用它:
t = "He got 10/19 questions right."
t2 = "He/she got 10/19 questions right"
for q in [t,t2]:
# split whole string at spaces
# split each part at /
# only keep parts that contain / but not at 1st position and only consists
# out of numbers elsewise
numbers = [x.split("/") for x in q.split()
if "/" in x and all(c in "0123456789/" for c in x)
and not x.startswith("/")]
if numbers:
print(numbers[0][0])
Output: 输出:
10
10
res = re.search('(\d+)/\d+', r'He got 10/19 questions right.')
res.groups()
('10',)
import re
myString = "He got 10/19 questions right."
oldnumber = re.findall('[0-9]+/', myString) #find one or more digits followed by a slash.
newNumber = oldnumber[0].replace("/","") #get rid of the slash.
print(newNumber)
>>>10
Find all numbers before the forward-slash and exclude the forward-slash by using start-stop parentheses. 在正斜杠之前找到所有数字,并使用起止括号将正斜杠排除在外。
>>> import re
>>> myString = 'He got 10/19 questions right.'
>>> stringNumber = re.findall('([0-9]+)/', myString)
>>> stringNumber
['10']
This returns all numbers ended with a forward-slash, but in a list of strings. 这将返回所有以正斜杠结尾但在字符串列表中的数字。 if you want integers, you should
map
your list with int
, then make a list
again. 如果需要整数,则应将列表与
int
map
,然后再次创建一个list
。
>>> intNumber = list(map(int, stringNumber))
>>> intNumber
[10]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.