显示正则表达式匹配的字符

时间:2013-02-08 20:13:41

标签: ruby regex

是否可以显示正则表达式匹配的字符?我有下面的字符串,我希望在匹配前显示3-5个字符时替换"change"的每次出现。

string = "val=change anotherval=change stringhere:change: foo=bar foofoo=barbar"

到目前为止我有什么

while line.match(/change/)
  printf "\n\n Substitute the FIRST change below:\n"
  printf "#{line}\n"

  printf "\n\tSubstitute => "
  substitution = gets.chomp

  line = line.sub(/change/, "#{substitution}")
end

3 个答案:

答案 0 :(得分:4)

如果你想降低和肮脏的Perl风格:

before_chars = $`[-3, 3]

这是模式匹配前的最后三个字符。

答案 1 :(得分:0)

您可能会使用以下方式给出的gsub!块:

line = "val=change anotherval=change stringhere:change: foo=bar foofoo=barbar"

# line.gsub!(/(?<where>.{0,3})change/) {
line.gsub!(/(?<where>\S+)change/) {

  printf "\n\n Substitute the change around #{Regexp.last_match[:where]} => \n"
  substitution = gets.chomp

  "#{Regexp.last_match[:where]}#{substitution}"
}

puts line

产量:

 Substitute the change around val= => 
111
 Substitute the change around anotherval= => 
222
 Substitute the change around stringhere: => 
333

val=111 anotherval=222 stringhere:333: foo=bar foofoo=barbar

gsub!会替换相应的匹配,而更合适的模式\S+而非注释.{0,3}将使您能够打印出人类可读的提示。

答案 2 :(得分:0)

替代方案:使用$ 1匹配变量

tadman的回答使用特殊的prematch变量( $`)。 Ruby还会在一个带编号的变量中存储一个捕获组,这可能同样神奇,但可能更直观。例如:

string = "val=change anotherval=change stringhere:change: foo=bar foofoo=barbar"
string.sub(/(.{3})?change/, "\\1#{substitution}")
$1
# => "al="

无论您使用何种方法,请确保在上次尝试的匹配失败时明确检查nils的匹配变量。