Search code examples
rubyregexstring-parsing

ruby start_with?(), end_with?()


I have a document with subject headers being enclosed in "|" characters.

E.g. "| LINKS |"

I want to check the string if it begins and ends with "|" character to verify that the particular document's subject header is valid. How do I do so ?

Source:

@filetarget = " < document file location here > "

@line = ""

file = File.new(@filetarget)

while (@line = file.gets)
   if((@line.start_with?("|")) and (@line.end_with?("|")))
      puts "Putting: " + @line
   end
end

Document text for parsing:

| LINKS |

http://www.extremeprogramming.org/  <1>

http://c2.com/cgi/wiki?ExtremeProgramming  <2>

http://xprogramming.com/index.php  <3>

| COMMENTS |

* Test comment
* Test comment 2
* Test comment 3

Solution

  • You can just use a simple regular expression:

    if line =~ /^\|.*\|$/
    

    That way you can verify other things, like that the header has to be all caps and needs spaces around it (/^\|\s[A-Z]+\s\|$/).