[英]Replace the first 3 white space coming with a character and ignore other white spaces in a text line with python
[英]Search between character and first white space
我试图从这个字符串 REG/123 中提取数字,它在 REG/ 和一个空格之间。
我尝试了以下代码,尽管它们只占用行中的最后一个空格。
test=line[line.find("REG/")+len("REG/"):line.rfind(" ")]
test=re.search('REG/(.*)" "',line)
我最终做的是以下代码,它对我有用,我用特定字符替换了空格,然后做了正则表达式。
line = line.replace(" ", "#")
test=re.search(r'REG/(.*?)#', line).group(1)
print(test)
对于像“REG/123”这样的模式,正则表达式将是r'^REG/\\d+$'
test=re.search(r'^REG/\\d+$',line)
获得所有匹配项后,您可以运行循环以通过使用.split("/")[1]
拆分字符串来仅提取数字
line = 'I am trying to extract the number from this string REG/123 which is between REG/ and a white space.'
number = re.search(r'(?<=\bREG/)\d+', line).group(0)
print(number)
输出:
123
解释:
(?<= # positive lookbehind, make sure we have before:
\b # a word boundary
REG/ # literally REG/ string
) # end lookbehind
\d+ # 1 or more digits
您可以使用正则表达式匹配字符从字符串中提取整数值。
text = "REG/123"
re.search(r'\d+', text)
o/p: 123
or
re.findall(r'\d+', text)
o/p: 123
解释:
"\\d" - 匹配任何十进制数字; 这相当于类 [0-9]。
"+" - 一个或多个整数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.