繁体   English   中英

使用Ruby中的正则表达式从字符串中获取子字符串

[英]Get substring from string using regex in ruby

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:(.*?):/匹配项

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

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

您也可以使用字符类[\\s\\S]代替. 具有类似的效果,而无需使用multiline修饰符:

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

以多行模式运行regex应该可以解决以下问题:

(?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

暂无
暂无

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

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