【问题标题】:Get substring from string using regex in ruby在ruby中使用正则表达式从字符串中获取子字符串
【发布时间】:2018-05-07 15:00:47
【问题描述】:
ex = "g4net:HostName=abc}\n Unhandled Exception: \nSystem.NullReferenceException: Object reference not set to an";
puts ex[/Unhandled Exception:(.*?):/,0]

/Unhandled Exception:(.*?):/ 应该与 \nSystem.NullReferenceException 匹配(在 rubular 中测试)但它一直没有显示任何结果。

我是红宝石新手。请帮助我如何从给定的字符串中提取 /Unhandled Exception:(.*?):/ 的匹配项

【问题讨论】:

  • Rubular 从字面上解释您的\n。您必须单独插入行以获得相同的行为:rubular.com/r/MOdKAd2Xnl。提示:. 仅在设置了 m 标志时才匹配换行符。
  • 如果你想匹配文本,请使用正向lookbehind:puts ex[/(?<=Unhandled Exception:).*?:/m]

标签: ruby regex substring


【解决方案1】:

在多行模式下运行正则表达式应该可以解决问题:

(?m)Unhandled Exception:(.*?):

代码:

re = /Unhandled Exception:(.*?):/m
str = 'g4net:HostName=abc}
 Unhandled Exception: 
System.NullReferenceException: Object reference not set to an
'

# Print the match result
str.scan(re) do |match|
    puts match.to_s
end

【讨论】:

    【解决方案2】:

    Ruby(和大多数其他语言)默认使用与换行符不匹配的正则表达式方言 .。在 Ruby 中,您可以使用 m(多行)修饰符:

    matchinfo = ex.match(/Unhandled Exception: (.*)/m)
    # Allow "." to match newlines ------------------^
    matchinfo[1] # => "\nSystem.NullRef..."
    

    你也可以使用字符类[\s\S]而不是.来达到类似的效果,而不需要多行修饰符:

    matchinfo = ex.match(/Unhandled Exception: ([\s\S]*)/)
    # Really match *any* character -------------^----^
    matchinfo[1] # => "\nSystem.NullRef..."
    

    【讨论】:

    • 很高兴看到您解释多行修饰符的作用。虽然它很简单,但似乎有很多困惑。我以前没见过[\s\S]。我猜[\w\W][\d\D] 会有同样的效果。
    猜你喜欢
    • 2019-05-02
    • 2017-06-07
    • 2011-05-06
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多