[英]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.