简体   繁体   English

此gsub和正则表达式如何工作?

[英]How does this gsub and regex work?

I'm trying to learn ruby and having a hard time figuring out what each individual part of this code is doing. 我正在尝试学习ruby,并且很难弄清楚这段代码的每个部分在做什么。 Specifically, how does the global subbing determine whether two sequential numbers are both one of these values [13579] and how does it add a dash ( - ) in between them? 具体来说,全局子集如何确定两个序号是否均为这些值之一[13579]以及如何在它们之间添加破折号( - )?

def DashInsert(num)
  num_str = num.to_s
  num_str.gsub(/([13579])(?=[13579])/, '\1-')
end
num_str.gsub(/([13579])(?=[13579])/, '\1-')
  • () called capturing group, which captures the characters matched by the pattern present inside the capturing group. ()称为捕获组,捕获与捕获组内存在的模式匹配的字符。 So the pattern present inside the capturing group is [13579] which matches a single digit from the given set of digits. 因此,捕获组中存在的模式为[13579] ,它与给定数字集中的单个数字匹配。 That corresponding digit was captured and stored inside index 1. 相应的数字被捕获并存储在索引1中。

  • (?=[13579]) Positive lookahead which asserts that the match must be followed by the character or string matched by the pattern inside the lookahead. (?=[13579])正向超前,它断言匹配必须跟随由超前内部的模式匹配的字符或字符串。 Replacement will occur only if this condition is satisfied. 仅在满足此条件时才进行更换。

  • \\1 refers the characters which are present inside the group index 1. \\1表示存在于组索引1中的字符。

Example: 例:

> "13".gsub(/([13579])(?=[13579])/, '\1-')
=> "1-3"

You may start with some random tests: 您可以从一些随机测试开始:

def DashInsert(num)
  num_str = num.to_s
  num_str.gsub(/([13579])(?=[13579])/, '\1-')
end

10.times{
  x = rand(10000)
  puts "%6i: %6s" % [x,DashInsert(x)]
}

Example: 例:

9633:  963-3
7774: 7-7-74
6826:   6826
7386:  7-386
2145:   2145
7806:   7806
9499:  949-9
4117: 41-1-7
4920:   4920
  14:     14

And now to check the regex. 现在检查正则表达式。

  1. ([13579]) take any odd number and remember it (it can be used later with \\1 ([13579])取一个奇数并记住它(以后可以与\\1一起使用
  2. (?=[13579]) Check if the next number is also odd, but don't take it (it still remains in the string) (?=[13579])检查下一个数字是否也为奇数,但不要接受(仍保留在字符串中)
  3. '\\1-' Output the first odd num and ab a - to it. '\\1-'向其输出第一个奇数和ab a-。

In other word: Puts a - between each two odds numbers. 换句话说:在每两个奇数之间插入一个-

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

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