re = /(?:^(R)\|(\d+)\|\^*([^|]*)\|([^|]*)\|(?:([^|]*)\|)?.*$)|(?:^(P)\|(\d+)\|\|(\d+).*$)/im
str = 'P|1||322061||^|||U
O|1||138||||||||||||O
R|1|^^^BE(B)||mmol/L||C||||||20150819144937
R|2|^^^BEecf||mmol/L||C
R|3|^^^Ca++|1.17|mmol/L
R|4|^^^Ca++(7.4)||mmol/L||C
R|5|^^^HCO23-||mmol/L||C
R|6|^^^HCO3std||mmol/L||C
R|7|^^^K+|5.0|mmol/L
R|8|^^^Na+|140|mmol/L
R|9|^^^SO2c||%||C
R|10|^^^TCO2||mmol/L||C
R|11|^^^THbc||g/dL||C
R|12|^^^Temp|37.0|C
'
# 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