删除R中字符串中大写字母的第一个实例之前的字符 [英] Remove characters preceding first instance of a capital letter in string in R
本文介绍了删除R中字符串中大写字母的第一个实例之前的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试删除字符串向量中每个字符串的第一个大写字母实例之前的所有字符:
I'm trying to remove all characters preceding the first instance of a capital letter for each string in a vector of strings:
x <- c(" its client Auto Group", "itself and Phone Company", ", client Large Bank")
我试过了:
sub('.*?[A-Z]', '', x)
但这会返回:
"uto Group" "hone Company" "arge Bank"
我需要它返回:
"Auto Group" "Phone Company" "Large Bank"
有什么想法吗?
谢谢.
推荐答案
您需要使用带有反向引用的捕获组:
You need to use a capturing group with a backreference:
sub("^.*?([A-Z])", "\\1", x)
这里,
^
- 字符串的开始.*?
- 尽可能少的任意 0+ 个字符([A-Z])
- 捕获组 1 捕获将在替换模式中使用\1
引用的大写 ASCII 字母.
^
- start of the string.*?
- any 0+ characters as few as possible([A-Z])
- Capture group 1 capturing an uppercase ASCII letter that will be referenced with\1
in the replacement pattern.
那么,我们通过反向引用恢复我们在结果中捕获的内容.
So, what we restore what we captured in the result with a backreference.
这篇关于删除R中字符串中大写字母的第一个实例之前的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文