搜索于字符和第一个空白位之间

2024-04-26 19:05:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从这个字符串REG/123中提取数字,这个字符串介于REG/和一个空格之间。你知道吗

我尝试了以下代码,尽管它们只占用行中的最后一个空格。你知道吗

test=line[line.find("REG/")+len("REG/"):line.rfind(" ")]

test=re.search('REG/(.*)" "',line)

Tags: 字符串代码testresearchlenline数字
3条回答

对于像'REG/123'这样的模式,regex将是r'^REG/\d+$'

test=re.search(r'^REG/\d+$',line)

获取所有匹配项后,可以运行循环,通过使用.split("/")[1]拆分字符串来仅提取数字

我最后做的是下面的代码,它对我来说是有效的,我用一个特定的字符替换了空格,然后做了regex。你知道吗

       line = line.replace(" ", "#")


       test=re.search(r'REG/(.*?)#', line).group(1)  

       print(test)
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

相关问题 更多 >