ex = "g4net:HostName=abc}\n Unhandled Exception: \nSystem.NullReferenceException: Object reference not set to an";
puts ex[/Unhandled Exception:(.*?):/,0]
/Unhandled Exception:(.*?):/
should match \\nSystem.NullReferenceException
(as tested in rubular) but it keeps displaying no result.
I'm new to ruby. Please help how can I extract a match for /Unhandled Exception:(.*?):/
from given string
Ruby (and most other languages) use regular expression dialects which do not match newline characters with .
by default. In Ruby you can use the m
(multiline) modifier:
matchinfo = ex.match(/Unhandled Exception: (.*)/m)
# Allow "." to match newlines ------------------^
matchinfo[1] # => "\nSystem.NullRef..."
You can also use the character class [\\s\\S]
instead of .
for similar effect, without the need for the multiline modifier:
matchinfo = ex.match(/Unhandled Exception: ([\s\S]*)/)
# Really match *any* character -------------^----^
matchinfo[1] # => "\nSystem.NullRef..."
Running the regex in multiline mode should solve the issue:
(?m)Unhandled Exception:(.*?):
Code:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.