排除某个字符串第二次出现后的所有内容 [英] Exclude everything after the second occurrence of a certain string

查看:54
本文介绍了排除某个字符串第二次出现后的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串

string <- c('a - b - c - d',
            'z - c - b',
            'y',
            'u - z')

我想对它进行子集化,以便在第二次出现"- "之后的所有内容都被丢弃.

I would like to subset it such that everything after the second occurrence of ' - ' is thrown away.

结果是这样的:

> string
[1]  "a - b" "z - c" "y"     "u - z"

我使用了 substr(x = string, 1, regexpr(string, pattern = '[^ - ]*$') - 4),但它排除了最后一次出现的 ' - ',这不是我想要的.

I used substr(x = string, 1, regexpr(string, pattern = '[^ - ]*$') - 4), but it excludes the last occurrence of ' - ', which is not what I want .

推荐答案

请注意,您不能使用 否定字符类 否定字符序列.[^ - ]*$ 匹配除空格以外的任何 0+ 个字符(是的,它也匹配 -,因为 - 创建了一个一个空格和一个空格之间的范围)后跟字符串标记的结尾($).

Note that you cannot use a negated character class to negate a sequence of characters. [^ - ]*$ matches any 0+ chars other than a space (yes, it matches -, too, because the - created a range between a space and a space) followed by the end of the string marker ($).

您可以使用带有以下正则表达式的 sub 函数:

You may use a sub function with the following regex:

^(.*? - .*?) - .*

替换为\1.请参阅正则表达式演示.

R 代码:

> string <- c('a - b - c - d', 'z - c - b', 'y', 'u - z')
> sub("^(.*? - .*?) - .*", "\\1", string)
[1] "a - b" "z - c" "y"     "u - z"

详情:

  • ^ - 字符串的开始
  • (.*? - .*?) - 第 1 组(在替换模式中使用 \1 反向引用引用)捕获任何 0+ 个字符 懒惰直到第一个空格,连字符,空格,然后是任何 0+ 个字符,直到下一个最左边出现的空格,连字符,空格
  • - - 一个空格、连字符和一个空格
  • .* - 直到字符串末尾的任何零个或多个字符.
  • ^ - start of a string
  • (.*? - .*?) - Group 1 (referred to with the \1 backreference in the replacement pattern) capturing any 0+ chars lazily up to the first space, hyphen, space and then again any 0+ chars up to the next leftmost occurrence of space, hyphen, space
  • - - a space, hyphen and a space
  • .* - any zero or more chars up to the end of the string.

这篇关于排除某个字符串第二次出现后的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆