删除最后一个空格之前的所有内容 [英] Remove everything before the last space

查看:95
本文介绍了删除最后一个空格之前的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串.我试图删除最后一个空格之前的所有字符串,但似乎无法实现.

I have a following string. I tried to remove all the strings before the last space but it seems I can't achieve it.

我试图关注这篇文章

使用gsub首先删除所有字符串R

str <- c("Veni vidi vici")


gsub("\\s*","\\1",str)

"Venividivici"

在删除最后一个空格之前的所有内容后,我只想剩下"vici"个字符串.

What I want to have is only "vici" string left after removing everything before the last space.

推荐答案

您的gsub("\\s*","\\1",str)代码使用对捕获组#1值的引用(由于您没有指定了模式中的任何捕获组.

Your gsub("\\s*","\\1",str) code replaces each occurrence of 0 or more whitespaces with a reference to the capturing group #1 value (which is an empty string since you have not specified any capturing group in the pattern).

您要匹配最后一个空格:

You want to match up to the last whitespace:

sub(".*\\s", "", str)

如果您不想在字符串末尾有空格时得到空白结果,请先修剪字符串:

If you do not want to get a blank result in case your string has trailing whitespace, trim the string first:

sub(".*\\s", "", trimws(str))

或者,使用方便的 stringi >包并带有简单的\S+模式(匹配1个或多个非空白字符):

Or, use a handy stri_extract_last_regex from stringi package with a simple \S+ pattern (matching 1 or more non-whitespace chars):

library(stringi)
stri_extract_last_regex(str, "\\S+")
# => [1] "vici"

请注意,.*尽可能匹配任何0+个字符(因为*是贪婪的量词,而TRE模式中的.匹配任何包含换行符的char),并首先捕获整个字符串.然后,由于正则表达式引擎需要将空白与\s匹配,因此开始回溯. regex引擎从字符串的末尾开始逐个字符地产生字符,它在最后一个空白处绊倒,并将其称为一天,返回随后被删除的匹配项.

Note that .* matches any 0+ chars as many as possible (since * is a greedy quantifier and . in a TRE pattern matches any char including line break chars), and grabs the whole string at first. Then, backtracking starts since the regex engine needs to match a whitespace with \s. Yielding character by character from the end of the string, the regex engine stumbles on the last whitespace and calls it a day returning the match that is removed afterwards.

请参见 R演示

此外,您可能希望在 regex调试器中查看回溯的工作方式:

Also, you may want to see how backtracking works in the regex debugger:

那些红色箭头显示了回溯步骤.

Those red arrows show backtracking steps.

这篇关于删除最后一个空格之前的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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