简体   繁体   English

从Ruby中的Regex获取字符串

[英]Get string from Regex in Ruby

I need to add a string to a regular expression in ruby, this is what Im trying to do (Im getting all the files in my directory, opening them, finding if they have a pattern, then modifying that pattern by adding to what already exists, to do this I need the actual string) 我需要在ruby中的正则表达式中添加一个字符串,这就是我正在尝试做的事情(我将所有文件放在目录中,打开它们,查找它们是否具有模式,然后通过添加到已经存在的模式来修改该模式,为此,我需要实际的字符串)

Dir["*"].each do |tFile|
  file = File.open(tFile, "rb")
  contents = file.read
  imageLine=/<img class="myclass"(.*)\/>/
  if(contents=~imageLine)
      puts contents.sub!(imageLine, "some string"+imageLine+"some other string")
  end
end

You can use sub or gsub with capture groups: 您可以将subgsub与捕获组一起使用:

"foo".gsub(/(o)/, '\1x')
=> "foxox"

For more information, consult the docs . 有关更多信息,请参阅docs

You're using sub! 您正在使用sub! which is the in-place modifier version. 这是就地修改器版本。 While this has its uses, the result of the method is not the string but an indication if anything was done or not. 尽管有其用途,但该方法的结果不是字符串,而是指示是否进行了任何操作。

The sub method is more appropriate for this case. sub方法更适合这种情况。 If you have multiple matches that have to be replaced, use gsub . 如果您有多个必须替换的匹配项,请使用gsub

When doing substitution you can either use the placeholders like \\1 to work with captured parts, where you capture using brackets in your regular expression, or the employ the block version to do more arbitrary manipulation. 进行替换时,可以使用\\1类的占位符来处理捕获的部分,在正则表达式中使用方括号捕获,也可以使用块版本进行更多的任意操作。

IMAGE_REGEXP = /<img class="myclass"(.*)\/>/

Dir["*"].each do |tFile|
  File.open(tFile, "rb") do |in|
    puts in.read.gsub(IMAGE_REGEXP) { |s| "some string#{s}some other string" }
  end
end

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

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