gpt4 book ai didi

正则表达式 - 在第二次出现之前返回所有

转载 作者:行者123 更新时间:2023-12-03 21:00:27 24 4
gpt4 key购买 nike

鉴于此字符串:

DNS000001320_309.0/121.0_t0

我将如何在第二次出现“_”之前返回所有内容?
DNS000001320_309.0/121.0

我正在使用 R。

谢谢。

最佳答案

以下脚本:

s <- "DNS000001320_309.0/121.0_t0"
t <- gsub("^([^_]*_[^_]*)_.*$", "\\1", s)
t

将打印:
DNS000001320_309.0/121.0

正则表达式的快速解释:
^         # the start of the input
( # start group 1
[^_]* # zero or more chars other than `_`
_ # a literal `_`
[^_]* # zero or more chars other than `_`
) # end group 1
_ # a literal `_`
.* # consume the rest of the string
$ # the end of the input

替换为:
\\1       # whatever is matched in group 1

如果少于 2 个下划线,则字符串不会更改。

关于正则表达式 - 在第二次出现之前返回所有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7449564/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com