我的目标是用一个符号代替一个字符串,并重复该符号与字符串中相同数量的字符,类似于将字母替换为大写字母的
这是否可能?我主要考虑使用
我假设答案可能是否定的,因为选择似乎很有限(
\\U\\1
。如果我的模式是"...(*)..."
,那么我对(*)
捕获的内容的替换将类似于x\\q1
或{\\q1}x
,因此我将得到与*
所捕获的字符数量相同的x
。这是否可能?我主要考虑使用
sub,gsub
方法,但您可以使用其他库,如stringi,stringr
等来回答。您可以方便地使用perl = TRUE
或perl = FALSE
和其他选项。我假设答案可能是否定的,因为选择似乎很有限(
?gsub
)。a replacement for matched pattern in sub and gsub. Coerced to character if possible. For fixed = FALSE this can include backreferences "\1" to "\9" to parenthesized subexpressions of pattern. For perl = TRUE only, it can also contain "\U" or "\L" to convert the rest of the replacement to upper or lower case and "\E" to end case conversion. If a character vector of length 2 or more is supplied, the first element is used with a warning. If NA, all elements in the result corresponding to matches will be set to NA.
主要的量词符号是(?base::regex
):
?
The preceding item is optional and will be matched at most once.
*
The preceding item will be matched zero or more times.
+
The preceding item will be matched one or more times.
{n}
The preceding item is matched exactly n times.
{n,}
The preceding item is matched n or more times.
{n,m}
The preceding item is matched at least n times, but not more than m times.
好的,但似乎这是一个选项(在PCRE
中没有,不确定是否在PERL
或其他地方有...)(*)
,它捕获了星号量词能够匹配的字符数(我在https://www.rexegg.com/regex-quantifier-capture.html找到了这个选项),因此可以使用\q1
(同一参考资料)引用第一个捕获的量词(以及\q2
等)。我还阅读到(*)
等价于{0,}
,但我不确定这对我感兴趣的内容是否真实。
编辑更新:
由于被评论者询问,我通过这个有趣问题提供了一个具体示例。 我稍微修改了一下例子。假设我们有字符串a <- "I hate extra spaces elephant"
,因此我们想要保留单词之间唯一的空格,每个单词的前5个字符(直到原始问题为止),但然后是每个其他字符的句点(不确定这是否是原始问题所期望的,但无关紧要),因此结果字符串将是"I hate extra space. eleph..."
(对于spaces
中的最后一个s
和elephant
末尾的三个字母ant
,分别用一个.
和3个.
表示)。因此,我首先保留了前5个字符。
gsub("(?<!\\S)(\\S{5})\\S*", "\\1", a, perl = TRUE)
[1] "I hate extra space eleph"
我该如何用点号或其他符号替换\\S*
中精确数量的字符?
?base::regex
中阅读了有关量词的内容,但没有找到有关在替换中使用它们的任何信息”即可。 - Gregor Thomas