使用空格和大写字母分割字符串

时间:2018-07-05 12:02:31

标签: r regex string split

我正在尝试将我的字符串分成多行。字符串看起来像这样:

x <- c("C 10.1 C 12.4","C 12", "C 45.5 C 10")  

代码段:

strsplit(x, "//s")[[3]]

结果:

"C 45.5 C 10"

预期的输出:像这样将字符串分成多行:

"C 10.1"
"C 12.4"
"C 12"
"C 45.5"
"C 10" 

问题是如何分割字符串?

提示:在我们的例子中,有一个空格,然后是“ C”字符。知道怎么做的人吗?

2 个答案:

答案 0 :(得分:2)

您可以使用

unlist(strsplit(x, "(?<=\\d)\\s+(?=C)", perl=TRUE))

输出:

[1] "C 10.1" "C 12.4" "C 12"   "C 45.5" "C 10" 

请参见online R demoregex demo

(?<=\\d)\\s+(?=C)正则表达式匹配1个或多个空格字符(\\s+),这些空格字符紧跟数字((?<=\\d))并紧跟C。 / p>

如果C可以是任何大写ASCII字母,请将C替换为[A-Z]

答案 1 :(得分:1)

更复杂的表达式,但在正则表达式方面更容易:

const count = 5;
const neededValue = 5;
//create button
var container_content = document.querySelector(".container-content");
for (i = 0; i < 25; i++) {
  var btn = document.createElement("input");
  btn.type = "button";
  container_content.appendChild(btn);
}
//set class and value into container
var btnAll = document.getElementsByTagName("input");
for (j = 0; j < btnAll.length; j++) {
    btnAll[j].setAttribute("class", "button");
    //i was really confusing in this case
    btnAll[j].setAttribute("value", 1)
}
for (let i = 0; i < count; i++) {
  let randomIndex = Math.floor(Math.random() * btnAll.length);
  btnAll[randomIndex].setAttribute("value", neededValue)
}