re = /(?=\S)(?<text>(?<comment>(?<open>[#;]+)(?:[^\S\r\n]*)(?<value>.+))|(?<section>(?<open>\[)(?:\s*)(?<value>[^\]]*\S+)(?:[^\S\r\n]*)(?<close>\]))|(?<entry>(?<key>[^=\r\n\[\]]*\S)(?:[^\S\r\n]*)(?<delimiter>:|=)(?:[^\S\r\n]*)(?<value>[^#;\r\n]*))|(?<undefined>.+))(?<=\S)|(?<linebreaker>\r\n|\n)|(?<whitespace>[^\S\r\n]+)/i
str = '; Comment above the section
Key0=Value0
[Section 1]
Key=Value
[EmptySection]
Dummy text
;Commented Key=Value
;The following empty lines are ignored
;
#
[ Section 2 ]#Comment after [section];
Key 1 = Value 1
Key2 = Value 2 and [text in square brackets]
EmptyKey=
[];Noname section ignored
[ Section2 ] Dummy text after section
Key3 =Value 3 (symbols [;] are included)
#Key4 = Value 4 has been commented
Dummy text before section [ Sectionnum3 ]
Key 5 = Value 5
Key6 =Value6 '
# Print the match result
str.scan(re) do |match|
puts match.to_s
end
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Ruby, please visit: http://ruby-doc.org/core-2.2.0/Regexp.html