如何使用组捕获在行尾选择单词?

时间:2016-06-10 11:11:43

标签: ruby regex

我很难使用群组捕捉。我有以下文字:

 1       2015-08-09         1000 2015-11-22 - 2015-08-09
 1       2015-11-22          100 2015-12-12 - 2015-11-22
 1       2015-12-12          200 2015-12-16 - 2015-12-12
 1       2015-12-16         2392 2015-12-27 - 2015-12-27
 1       2015-12-27          123         NA
 7       2015-08-09          200 2015-09-09 - 2015-08-09
 7       2015-09-09         1000 2015-09-27 - 2015-09-09
 7       2015-09-27       100018 2015-12-25 - 2015-09-27
 7       2015-12-25         1000         NA
 8       2015-08-27         1000  2015-12-07 - 2015-08-27
 8       2015-12-07        10000  2016-02-18 - 2015-12-07
 8       2016-02-18          796   2016-04-31- 2016-02-18     
 8       2016-04-31        10000         NA
15       2015-10-10         1500  2015-10-30 - 2015-10-10
15       2015-10-30         1000         NA

在这种情况下,我需要提取供应商场地

我正在尝试使用类似class Rename < ActiveRecord::Migration def change rename_table :users, :vendors rename_table :places, :venues end end 的内容,但无济于事。

我如何实现这一目标?

4 个答案:

答案 0 :(得分:2)

这样的事可能适合你:

/rename_table.+:(\S+)/g

它会在匹配组:中存储以rename_table vendorsvenues$1)为格式的[{username: "tester", group: "default"}, {username: "tester1", group: "admin"} etc...] 表格行的前一个单词。

Try it online

答案 1 :(得分:1)

\b(rename_table.*\,.*\:)(.*)/g

匹配组$ 1

您可以在https://regex101.com/r/pN9bO4/1

进行测试

答案 2 :(得分:1)

您不需要正则表达式:

str = %q{
class Rename < ActiveRecord::Migration
  def change
    rename_table :users, :vendors
    rename_table :places, :venues
  end
end
}

str.each_line do |line|
  puts line.split[-1] if line.lstrip.start_with? 'rename_table'
end

--output:--
:vendors
:venues

在任何情况下,正则表达式中的组都是([]+)。括号是特殊的正则表达式字符,它们代表字符类,您可以在其中指定要匹配的字符,例如[xyz]。该字符类将匹配一个xyz字符。在您的情况下,字符类为空,这在ruby 2.2中产生错误:

  

empty char-class:/ rename_table。*([] +)$ /

基本上,红宝石说,Wtf??! You specified a character class with no characters. Are you really trying to say, I want to match one character that is in the character class consisting of no characters?. I don't think so! Error! Error! Error!

答案 3 :(得分:1)

▶ text.scan(/rename_table.+:(\w+)\s*$/).flatten
#⇒ [
#  [0] "vendors",
#  [1] "venues"
# ]