关于正则表达式:从字符串中提取两个单词之间的子字符串

Extract a substring between two words from a string

我有以下字符串:

1
string ="asflkjsdhlkjsdhglk<body>Iwant\\to+extr@ctth!sstr|ng<body>sdgdfsghsghsgh"

我想提取两个 <body> 标签之间的字符串。我要找的结果是:

1
substring ="<body>Iwant\\to+extr@ctth!sstr|ng<body>"

注意两个<body>标签之间的子串可以包含字母、数字、标点符号和特殊字符。

有没有简单的方法可以做到这一点?谢谢!


这里是正则表达式的方式:

1
regmatches(string, regexpr('<body>.+<body>', string))


1
regex = '<body>.+?<body>'

你想要非贪婪的 (.+?),这样它就不会将尽可能多的 <body> 标签分组。

如果您只使用没有辅助功能的正则表达式,您将需要一个捕获组来提取所需的内容,即:

1
regex = '(<body>.+?<body>)'

strsplit() 应该可以帮助您:

1
2
3
4
5
6
>string ="asflkjsdhlkjsdhglk<body>Iwant\\to+extr@ctth!sstr|ng<body>sdgdfsghsghsgh"
>x = strsplit(string, '<body>', fixed = FALSE, perl = FALSE, useBytes = FALSE)
[[1]]
[1]"asflkjsdhlkjsdhglk"        "Iwant\\to+extr@ctth!sstr|ng""sdgdfsghsghsgh"  
> x[[1]][2]
[1]"Iwant\\to+extr@ctth!sstr|ng"

当然,这会为您提供字符串的所有三个部分,并且不包括标签。


我相信马修和史蒂夫的回答都是可以接受的。这是另一种解决方案:

1
2
3
4
5
6
7
string ="asflkjsdhlkjsdhglk<body>Iwant\\to+extr@ctth!sstr|ng<body>sdgdfsghsghsgh"

regmatches(string, regexpr('<body>.+<body>', string))

output = sub(".*(<body>.+<body>).*","\\\\1", string)

print (output)