简体   繁体   English

仅替换括号(R)中的某些字符

[英]Replacing only certain characters inside brackets (R)

I'm finding a bit difficult to write a regex expression that converts a string of the type: 我发现编写正则表达式来转换类型的字符串有点困难:

[1] "[hola;adios] address1;[hola;adios] address2"

into: 成:

[1] "[hola|adios] address1;[hola|adios] address2"

that is, replacing the semicolons inside the brackets into vertical bars. 也就是说,将括号内的分号替换为竖线。 The attempts I've made either fail to replace only the semicolons inside the brackets (the ones outside are also replaced), or they replace the entire substring [hola;adios] for a vertical bar. 我所做的尝试要么无法仅替换括号内的分号(外部的分号也被替换了),要么它们替换了整个竖线的子字符串[hola; adios]。

I'd be very grateful if someone could give me some pointers as to how to accomplish this task using the R language 如果有人可以给我一些有关如何使用R语言完成此任务的指导,我将不胜感激

You could try the below gsub commands. 您可以尝试以下gsub命令。

> x <- '[hola;adios] address1;[hola;adios] address2'
> gsub(";(?=[^\\[\\]]*\\])", "|", x, perl=T)
[1] "[hola|adios] address1;[hola|adios] address2"

;(?=[^\\\\[\\\\]]*\\\\]) matches all the semicolons only if it's followed by , ;(?=[^\\\\[\\\\]]*\\\\])仅在其后跟有匹配所有分号,

  • [^\\[\\]]* any character but not [ or ] , zero or more times. [^\\[\\]]*任意字符,但不包括[] ,零次或多次。
  • \\] And a closing square bracket. \\]和一个右方括号。 So this would match all the semicolons which are present inside the [] , square brackets. 因此,这将匹配[]方括号内的所有分号。 (?=...) called positive lookahead assertion. (?=...)称为正向超前断言。

DEMO DEMO

OR 要么

> gsub(";(?![^\\[\\]]*\\[)", "|", x, perl=T)
[1] "[hola|adios] address1;[hola|adios] address2"

(?!...) called negative lookahead which does the opposite of positive lookahead assertion. (?!...)称为否定先行,与肯定先行断言相反。

Using the gsubfn package, you could avoid having to use lookarounds. 使用gsubfn软件包,您可以避免使用环顾四周

x <- '[hola;adios] address1;[hola;adios] address2'
gsubfn('\\[[^]]*]', ~ gsub(';', '|', x), x)
# [1] "[hola|adios] address1;[hola|adios] address2"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM