在 R 中使用 stringr 的带有非捕获组的正则表达式 [英] Regex with non-capturing group using stringr in R

查看:52
本文介绍了在 R 中使用 stringr 的带有非捕获组的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将非捕获组与 stringr 包中的 str_extract 函数一起使用.下面是一个例子:

I am trying to use non-capturing groups with the str_extract function from the stringr package. Here is an example:

library(stringr)
txt <- "foo"
str_extract(txt,"(?:f)(o+)")

返回

"foo"

虽然我希望它只返回

"oo"

喜欢这篇文章:https://stackoverflow.com/a/14244553/3750030

如何在 R 中使用非捕获组从返回值中删除组的内容,同时使用它进行匹配?

How do i use non-capturing groups in R to remove the content of the groups from the returned value while using it for matching?

推荐答案

当你使用正则表达式 (?:f)(o+) 这不会捕获但是它肯定会匹配.

When you are using regex (?:f)(o+) this won't Capture but it will match it for sure.

捕获的意思是存储在内存中用于后向引用,这样它就可以用于同一字符串中的重复匹配或替换捕获的字符串.

What capturing means is storing in memory for back-referencing, so that it can be used for repeated match in same string or replacing captured string.

喜欢这篇文章:https://stackoverflow.com/a/14244553/3750030

你误解了那个答案.Non-Capturing 组并不意味着 Non-Matching. 它在 $1 ( group 1 ) 中被捕获,因为在它之前没有任何组.

You misunderstood that answer. Non-Capturing groups doesn't means Non-Matching. It's captured in $1 ( group 1 ) because there is no group prior to it.

如果您希望匹配假设 B 后跟 A 那么您应该像这样使用 positive lookbehind.

If you wish to Only match suppose B followed by A then you should use positive lookbehind like this.

正则表达式: (?<=f)(o+)

说明:

  • (?<=f) 这将寻找 f 出现在以下标记后面但不会匹配.

  • (?<=f) This will look for f to be present behind the following token but won't match.

(o+) 如果前一个条件为真,这将匹配并捕获为组(此处为 $1).

(o+) This will match and capture as group (here in $1)if previous condition is true.

Regex101 演示

这篇关于在 R 中使用 stringr 的带有非捕获组的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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