去掉括号内的数字和逗号 (正则表达式)

huangapple go评论60阅读模式
英文:

Remove numbers and commas inside parenthesis (regex)

问题

我想提取这个测试向量中的数字。

我已经尝试过这个:

test <- c("(15, 80)","(100, 60)","(40, 40)","(30, 20)","(10, 60)")
stringr::str_extract(test, "[0-9:0-9:0-9], [0-9:0-9:0-9]")

但是返回相同的输入。我需要一个输出像这样:

"15, 80"    "100, 60"    "40, 40"    "30, 20"    "10, 60"
英文:

I want to extract the numbers inside this test vector.

I've already tried this:


test &lt;- c(&quot;(15, 80)&quot;,&quot;(100, 60)&quot;,&quot;(40, 40)&quot;,&quot;(30, 20)&quot;,&quot;(10, 60)&quot;)
stringr::str_extract(test, &quot;[0-9:0-9:0-9], [0-9:0-9:0-9]&quot;)

But return the same input. I need an output like this:

&quot;15, 80&quot; &quot;100, 60&quot; &quot;40, 40&quot; &quot;30, 20&quot; &quot;10, 60&quot;

答案1

得分: 2

Using a regex replacement approach with gsub() we can try:

<!-- language: r -->

test <- c("(15, 80)","(100, 60)","(40, 40)","(30, 20)","(10, 60)")
output <- gsub("^\(|\)$", "", test)
output

[1] "15, 80" "100, 60" "40, 40" "30, 20" "10, 60"

英文:

Using a regex replacement approach with gsub() we can try:

<!-- language: r -->

test &lt;- c(&quot;(15, 80)&quot;,&quot;(100, 60)&quot;,&quot;(40, 40)&quot;,&quot;(30, 20)&quot;,&quot;(10, 60)&quot;)
output &lt;- gsub(&quot;^\\(|\\)$&quot;, &quot;&quot;, test)
output

[1] &quot;15, 80&quot;  &quot;100, 60&quot; &quot;40, 40&quot;  &quot;30, 20&quot;  &quot;10, 60&quot;

答案2

得分: 2

trimws 可以在这种情况下工作。

trimws(test, whitespace = "[()]")
#[1] "15, 80"  "100, 60" "40, 40"  "30, 20"  "10, 60" 
英文:

In this case trimws would work.

trimws(test, whitespace = &quot;[()]&quot;)
#[1] &quot;15, 80&quot;  &quot;100, 60&quot; &quot;40, 40&quot;  &quot;30, 20&quot;  &quot;10, 60&quot; 

答案3

得分: 2

Using str_remove

library(stringr)
str_remove_all(test, "[()]")
[1] "15, 80"  "100, 60" "40, 40"  "30, 20"  "10, 60"

(Note: I've translated the code part as requested.)

英文:

Using str_remove

library(stringr)
 str_remove_all(test, &quot;[()]&quot;)
[1] &quot;15, 80&quot;  &quot;100, 60&quot; &quot;40, 40&quot;  &quot;30, 20&quot;  &quot;10, 60&quot; 

答案4

得分: 1

你可以尝试使用 trimwschartr 函数:

> trimws(chartr("()", " ", test))
[1] "15, 80" "100, 60" "40, 40" "30, 20" "10, 60"
英文:

You can try trimws along with chartr

&gt; trimws(chartr(&quot;()&quot;, &quot;  &quot;, test))
[1] &quot;15, 80&quot;  &quot;100, 60&quot; &quot;40, 40&quot;  &quot;30, 20&quot;  &quot;10, 60&quot;

huangapple
  • 本文由 发表于 2023年3月23日 11:31:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75819034.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定