0

我正在查看 odf 公式中的代码,看起来有点像这样:{500mgl} over {4.05grams} 例子

我想在 R 中使用带有 gsub 的正则表达式将所有带有模式的元素括在括号中

([0-9]+)([A-Za-z]+)

以避免某些单位不显示在分母中。但是,如果我这样做,各个单位最终将与实数分开: 4,{0.5g} 所以我想首先用逗号将数字括起来:

a<-"4,05g"
gsub("([0-9]+)(\\,)([0-9]+)([A-Za-z]+)","{\\1\\2\\3\\4}",a)

然后,用括号括起来模式:

([0-9]+)([A-Za-z]+)

但前提是模式前没有左括号。我尝试在网上搜索回溯语法如何与正则表达式一起工作,但是,我对它在 R 的 gsub 中的工作方式感到非常困惑。我试过这样的事情:

gsub("([^\\.])([0-9]+)([A-Za-z]+)","{\\2\\3}",a)
gsub("(?[\\.])([0-9]+)([A-Za-z]+)","{\\2\\3}",a)
gsub("(!\\.?)([0-9]+)([A-Za-z]+)","{\\2\\3}",a)

但老实说,我不知道我在做什么。

编辑:我认为前一个字符的豁免必须不是括号而是逗号。这样就可以避免输出

"0,3g
" 0,{3g}"

但能够做到

"30g"
"{30g}"
4

1 回答 1

0

You can use

x <- "4,05g"
gsub("(\\d+(?:,\\d+)?[[:alpha:]]*)", "{\\1}", x)

See the R demo and the regex demo.

Details:

  • ( - Group 1 start (necessary as gsub does not support backreferences to the whole match):
    • \d+ - one or more digits
    • (?:,\d+)? - an optional sequence of a comma and one or more digits
    • [[:alpha:]]* - zero or more letters
  • ) - end of the group.

The \1 in the replacement is the value of Group 1.

于 2021-11-30T08:44:36.563 回答