在r中的最后一个图案的最后一次出现之后,删除字符串中的所有字符

发布于 2025-01-27 07:54:16 字数 228 浏览 2 评论 0原文

我想在字符串中的特定模式的最后一个特定模式之后删除所有

字符 代码>

我想在模式的最后一次出现之后删除所有内容“ ge” < /code>,最终以:

“ asdsads dfdsfd&gt; x 442 /&lt; sdasvre(geqwe)ge ge ge ge ge ge ge ge ge ge''

I want to remove all the characters after the last ocurrence of a specific pattern in a string, in R.

For example:

string = "asdsads dfdsfd>x 442 /<sdasvre (geqwe) ge ge ge regthyty "

I would like to remove everything after the last ocurrence of the pattern "ge" and end up with:

"asdsads dfdsfd>x 442 /<sdasvre (geqwe) ge ge ge".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

悲喜皆因你 2025-02-03 07:54:16

您可以使用捕获组在最后一个“ GE”(^(。*GE))之前捕获所有字符串,并将整个内容替换为该捕获组(\\ 1 )。

sub('^(.*ge).+
, '\\1', string)
[1] "asdsads dfdsfd>x 442 /<sdasvre (geqwe) ge ge ge"

You can use a capture group to capture all strings before the last "ge" (^(.*ge)), and replace that whole thing with that capture group (\\1).

sub('^(.*ge).+
, '\\1', string)
[1] "asdsads dfdsfd>x 442 /<sdasvre (geqwe) ge ge ge"
小清晰的声音 2025-02-03 07:54:16

您可以在这里使用负面的lookahead:

string <- "asdsads dfdsfd>x 442 /<sdasvre (geqwe) ge ge ge regthyty "
output <- sub("\\bge (?!.*\\bge\\b).*", "ge", string, perl=TRUE)
output

[1] "asdsads dfdsfd>x 442 /<sdasvre (geqwe) ge ge ge"

You could use a negative lookahead here:

string <- "asdsads dfdsfd>x 442 /<sdasvre (geqwe) ge ge ge regthyty "
output <- sub("\\bge (?!.*\\bge\\b).*", "ge", string, perl=TRUE)
output

[1] "asdsads dfdsfd>x 442 /<sdasvre (geqwe) ge ge ge"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文