简体   繁体   English

如何使用gsub将正则表达式红宝石替换为第10组?

[英]how I could regex ruby replace by group 10 using gsub?

Im trying to gsub replace a string using a group 10 but instead of this ruby replace by group 1 and 0 I use this in gsub replacement 我试图使用组10 gsub替换字符串,但不是用组1和0将此红宝石替换,而是在gsub替换中使用它

gsub   \\10xp
  "smnm nmnmn nmnmn dsdsf sffddf sffdfd dfsff fdsdsfd fsdds ssfsff".gsub(/(\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+)/,"\\10xp")  

for replace and obtain the group 1 and the string "0xp" 用于替换并获取组1和字符串“ 0xp”

How I could solve this 我该如何解决

Please help me 请帮我

Not sure how to reference a double digit capture group, but you can always just reference a name with something like: 不确定如何引用两位数捕获组,但是您始终可以仅引用具有以下内容的名称:

"smnm nmnmn nmnmn dsdsf sffddf sffdfd dfsff fdsdsfd fsdds ssfsff".
  gsub(/(\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (?<ten>\S+)/,
       '\k<ten>xp')
# "ssfsffxp"

No one known regex engine does support unnamed groups beyond [0..9] region. 没有一个已知的正则表达式引擎不支持[0..9]区域以外的未命名组。 Use named_captures instead, or use uncaptured groups (?:...) , or use wiser regex: 请改用named_captures或使用未捕获的组(?:...)或使用更明智的正则表达式:

"smnm nmnmn nmnmn dsdsf sffddf sffdfd dfsff fdsdsfd fsdds ssfsff".
  gsub(/((?:\S+\s+){9})(\S+)/, "\\1 \\2xp")

#                      ⇑ second group
#                  ⇑⇑⇑ nine times
#        ⇑⇑⇑ don’t capture this!
#       ⇑ first group

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

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