Hey I have a huge text which goes 开发者_Python百科like this
some_data I POST postdata_1 IV POST postdata_4 III POST postdata_3 II POST postdata_2
So the post data has a the corresponding post number in Roman Numeral before the word 'POST'.
I want to put this into tags as
<post number>
I
</post number>
<post data>
post_data1
</post data>
And so on for every post..
Can someone help me out with a regular expression for this? I'm using Ruby
If I understand well, this will work how you expect:
roman_number = /M{0,3}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})/
regex = /(#{roman_number})\sPOST\s(.+?)(?=\s#{roman_number}\sPOST|$)/
str.scan(regex) do |post_number, post_data|
...
end
Roman numbers regex by paxdiablo, here.
It ain't a nice pretty regex but if I understand your input and requirements correctly... uhh "some_data" should be ignored right?
strin = "some_data I POST postdata_1 IV POST postdata_4 III POST postdata_3 II POST postdata_2"
while curmatch = strin.match(/ (.*?) POST (.*?) POST/) do
postnum = curmatch[1]
postdata = curmatch[2].reverse.sub(/.*? /, '').reverse
puts "<post number>#{postnum}</post number>"
puts "<post data>#{postdata}</post data>"
strin.sub!(" #{postnum} POST #{postdata}", '')
end
curmatch = strin.match(/ (.*?) POST (.*)/)
puts "<post number>#{curmatch[1]}</post number>"
puts "<post data>#{curmatch[2]}</post data>"
Output:
<post number>I</post number>
<post data>postdata_1</post data>
<post number>IV</post number>
<post data>postdata_4</post data>
<post number>III</post number>
<post data>postdata_3</post data>
<post number>II</post number>
<post data>postdata_2</post data>
But .. but .. it doesn't seem to need a regex ..
d = 'some_data I POST postdata_1 IV POST postdata_4' +
' III POST postdata_3 II POST postdata_2'
def fd
puts "<post data>\n #{
@pd[0..-2].to_a.join ' '
}\n</post data>\n" if @pd.to_a.length > 1
end
@pd = []
d.split.each_cons(2) do |n, p|
if p == 'POST'
fd
puts "<post number>\n #{n}\n</post number>\n"
@pd = []
else
@pd << p
end
end
@pd << ''
fd
精彩评论