正则表达式,使用python提取单词中特定符号后的所有单词

2024-09-28 05:25:43 发布

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

我必须在包含特殊字符(^)的单词后面提取一行中的所有单词。从以下行:

skipping root#14^wvoice as file not exists

node wroot#15^GetBuildType already complete

预期产量:

as file does not exists
already complete

我尝试使用正则表达式,如下所示:

(?<=\^\w).*

但得到的结果是:

wvoice as file not exists
GetBuildType already complete

先谢谢你。你知道吗


Tags: nodeasexistsnotroot单词filecomplete
2条回答

我可以给你

\^\w+\s(.*)

然后使用第二个匹配的组(index=1)

解释如下:link

你可以用

re.findall(r'\^\S*\s*(.*)', s)

或者,仅获取第一个匹配项:

m = re.search(r'\^\S*\s*(.*)', s)
if m:
    print(m.group(1))

参见regex demo。你知道吗

细节

  • \^-匹配的是文本^
  • \S*-0+非空白字符
  • \s*-然后是0+个空格字符
  • (.*)-捕获组1:除换行符(LF)之外的任何0个或更多字符。你知道吗

参见Python demo

import re
texts=['skipping root#14^wvoice as file not exists','node wroot#15^GetBuildType already complete']
for text in texts:
    m=re.search(r'\^\S*\s*(.*)', text)
    if m:
        print(m.group(1))

输出:

as file not exists
already complete

相关问题 更多 >

    热门问题