ruby start_with?(),end_with?()

tho*_*olh 3 ruby regex string-parsing

我有一个主题标题包含在"|"中的文档 字符.

例如"| LINKS |"

我想检查字符串是否以"|"开头和结尾 用于验证特定文档的主题标题是否有效的字符.我该怎么办?

资源:

@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
Run Code Online (Sandbox Code Playgroud)

用于解析的文档文本:

| 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
Run Code Online (Sandbox Code Playgroud)

And*_*imm 19

你试过RDoc了吗?

"| LINKS |".start_with?("|") # => true
"| LINKS |".end_with?("|") # => true
Run Code Online (Sandbox Code Playgroud)

  • @thotheloh:两个[`start_with?`](http://ruby-doc.org/core-1.8.7/classes/String.html#M000785)和[`end_with?`](http:// ruby​​-doc .org/core-1.8.7/classes/String.html#M000786)可在1.8.7中找到.那你究竟尝试了什么?你的字符串的开头或结尾有空格吗?或者也许是一个尾随换行符? (2认同)

Mic*_*ohl 5

你可以使用一个简单的正则表达式:

if line =~ /^\|.*\|$/
Run Code Online (Sandbox Code Playgroud)

这样你就可以验证其他东西,比如标题必须是全部大写并且需要它周围的空格(/^\|\s[A-Z]+\s\|$/).