我想知道一个字符串以多少个空格开头。这里有些例子:
string.1 <- " starts with 4 spaces"
string.2 <- " starts with only 2 spaces"
Run Code Online (Sandbox Code Playgroud)
我的尝试如下,但这两种情况都导致 1,我明白为什么会出现这种情况。
stringr::str_count(string.1, "^ ")
stringr::str_count(string.2, "^ ")
Run Code Online (Sandbox Code Playgroud)
我更希望有一个完全像这样但使用另一个正则表达式的解决方案。
该^ 模式与字符串开头的单个空格匹配,这就是两个测试用例都返回 的原因1。
要匹配字符串开头的连续空格,您可以使用
stringr::str_count(string.1, "\\G ")
Run Code Online (Sandbox Code Playgroud)
或者,要计算所有空格,
stringr::str_count(string.1, "\\G\\s")
Run Code Online (Sandbox Code Playgroud)
查看R 演示
该\G 模式在开始处匹配一个空格,并在成功匹配后由于锚点而匹配每个\G空格。
另一种方法:计算匹配的长度^\s+(字符串开头有 1 个或多个空白字符):
strings <- c(" starts with 4 spaces", " starts with only 2 spaces")
matches <- regmatches(strings, regexpr("^\\s+", strings))
sapply(matches, nchar)
# => 4 2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1432 次 |
| 最近记录: |