Regex 使用正则表达式分别替换分隔符的开头和结尾

Regex 使用正则表达式分别替换分隔符的开头和结尾,regex,r,Regex,R,我想替换以下表达式中的$分隔符 s <- "something before stuff $some text$ in between $1$ and after" s[1]“在1和之后填充一些文本” 我不是一个regex专业人士,也不知道如何分别处理分隔符的开头和结尾 有什么想法吗?谢谢你的时间 不成功的想法 为了记录在案,我完全不成功地提出了接近解决方案的想法: # Using lookarounds I get the following, but I would need it

我想替换以下表达式中的
$
分隔符

s <- "something before stuff $some text$ in between $1$ and after"
s[1]“在1和之后填充一些文本”
我不是一个regex专业人士,也不知道如何分别处理分隔符的开头和结尾

有什么想法吗?谢谢你的时间

不成功的想法

为了记录在案,我完全不成功地提出了接近解决方案的想法:

# Using lookarounds I get the following, but I would need it to be non-greedy
str_extract(s, perl("(?<=\\$).*(?=\\$)"))
"some text$ and some more $1"

# also greedy
str_match(s, "(\\$)(.*)(\\$)")
     [,1]                            [,2] [,3]                          [,4]
[1,] "$some text$ and some more $1$" "$"  "some text$ and some more $1" "$" 
#使用lookarounds我可以得到以下结果,但我需要它不是贪婪的

str_extract(s,perl)((?将此正则表达式与
gsub()
一起使用。替换使用反向引用(例如
\\1


ptn使用非贪婪运算符

\\$(.*?)\\$


哇。比我想象的简单!谢谢!你有没有试着简单地删除
$
?@casimirithippolyte。你的确切意思是什么?我想替换它们:)
# Using lookarounds I get the following, but I would need it to be non-greedy
str_extract(s, perl("(?<=\\$).*(?=\\$)"))
"some text$ and some more $1"

# also greedy
str_match(s, "(\\$)(.*)(\\$)")
     [,1]                            [,2] [,3]                          [,4]
[1,] "$some text$ and some more $1$" "$"  "some text$ and some more $1" "$" 
ptn <- "\\$(.*?)\\$" # Non-greedy find between delimiters
replacement <- "<B>\\1<E>"  # \\1 indicates back-reference
gsub(ptn, replacement, s)
[1] "something before stuff <B>some text<E> in between <B>1<E> and after"
\\$(.*?)\\$
\\$([^$]*)\\$