简体   繁体   English

R 中的捕获组

[英]Capturing Group in R

I have then following pattern Set(?:Value)?然后我有以下模式Set(?:Value)? in R as follows:在 R 中如下:

grepl('Set(?:Value)?', 'Set(Value)', perl=T)

this pattern is macthed by这种模式是由

1- Set
2- Set Value
3- Set(Value)

But I want to match only for two first cases and for for third case.但我只想匹配两个第一种情况和第三种情况。 Can anybody help me?有谁能够帮我?

Thank you谢谢

You can use您可以使用

grepl('^Set(?:\\s+Value)?$', x)
grepl('\\bSet(?!\\(Value\\))(?:\\s+Value)?\\b', x, perl=TRUE)

See regex demo #1 and regex demo #2 .请参阅正则表达式演示 #1正则表达式演示 #2

Details :详情

  • ^Set(?:\\s+Value)?$ - start of string, Set , an optional sequence of one or more whitespaces ( \s+ ) and a Value and then end of string ^Set(?:\\s+Value)?$ - 字符串的开头, Set ,一个或多个空格( \s+ )的可选序列和一个Value ,然后是字符串的结尾
  • \bSet(??\(Value\))(:?\s+Value)?\b : \bSet(??\(Value\))(:?\s+Value)?\b
    • \b - word boundary \b - 单词边界
    • Set - Set string Set - Set字符串
    • (?!\(Value\)) - no (Value) string allowed at this very location (?!\(Value\)) - 在这个位置不允许(Value)字符串
    • (?:\s+Value)? - an optional sequence of one or more whitespaces ( \s+ ) and a Value - 一个或多个空格( \s+ )和一个Value的可选序列
    • \b - word boundary \b - 单词边界

See an R demo :请参阅R 演示

x <- c("Set", "Set Value", "Set(Value)")
grep('^Set(?:\\s+Value)?$', x, value=TRUE)
## => [1] "Set"       "Set Value"
grep('\\bSet(?!\\(Value\\))(?:\\s+Value)?\\b', x, perl=TRUE, value=TRUE)
## => [1] "Set"       "Set Value"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM