如果句点前面或后面有句点,听起来您希望用空格替换句点,并且我假设一串句点之前不一定有冒号。如果是这样,这里有两种方法可以做到这一点。
str = "Domain:...................google.com"
使用Enumerable#each_cons 代替正则表达式
" #{str} ".each_char.each_cons(3).map { |before,ch,after|
ch=='.' && (before=='.' || after== '.') ? ' ' : ch }.join
#=> "Domain: google.com"
步骤如下。
s = " #{str} "
#=> " Domain:...................google.com "
a = s.each_char
#=> #<Enumerator: " Domain:...................google.com ":each_char>
e = a.each_cons(3)
#=> #<Enumerator: #<Enumerator: " Domain:...................google.com ":
# each_char>:each_cons(3)>
注意e 可以被认为是一个复合枚举器。我们可以通过将其转换为数组来查看此枚举器将生成的元素。
e.to_a
#=> [[" ", "D", "o"], ["D", "o", "m"], ["o", "m", "a"], ["m", "a", "i"],
# ["a", "i", "n"], ["i", "n", ":"], ["n", ":", "."], [":", ".", "."],
# [".", ".", "."], [".", ".", "."], [".", ".", "."], [".", ".", "."],
# [".", ".", "."], [".", ".", "."], [".", ".", "."], [".", ".", "."],
# [".", ".", "."], [".", ".", "."], [".", ".", "."], [".", ".", "."],
# [".", ".", "."], [".", ".", "."], [".", ".", "."], [".", ".", "."],
# [".", ".", "."], [".", ".", "g"], [".", "g", "o"], ["g", "o", "o"],
# ["o", "o", "g"], ["o", "g", "l"], ["g", "l", "e"], ["l", "e", "."],
# ["e", ".", "c"], [".", "c", "o"], ["c", "o", "m"], ["o", "m", " "]]
继续,
b = e.map { |before,ch,after| ch=='.' && (before=='.' || after== '.') ? ' ' : ch }
#=> ["D", "o", "m", "a", "i", "n", ":", " ", " ", " ", " ", " ", " ", " ",
# " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "g", "o",
# "o", "g", "l", "e", ".", "c", "o", "m"]
b.join
#=> "Domain: google.com"
使用正则表达式
r = /
(?<=\A|\.) # match the beginning of string or a period in a positive lookbehind
\. # match a period
| # or
\. # match a period
(?=\.|\z) # match a period or the end of the string
/x # free-spacing regex definition mode
str.gsub(r,' ')
#=> "Domain: google.com"