【问题标题】:ruby start_with?(), end_with?()红宝石 start_with?(), end_with?()
【发布时间】:2011-06-18 08:05:36
【问题描述】:

我有一个主题标题用“|”括起来的文档字符。

例如"| 链接 |"

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

来源:

@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

用于解析的文档文本:

| 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

【问题讨论】:

    标签: ruby regex string-parsing


    【解决方案1】:

    你试过RDoc吗?

    "| LINKS |".start_with?("|") # => true
    "| LINKS |".end_with?("|") # => true
    

    【讨论】:

    • @thotheolh:你应该在你的问题中这么说。是因为您没有使用 Ruby 1.9.2 吗? (您可以通过puts RUBY_VERSION查看)
    • 'starts_with' 和 'end_with' 是否受版本影响? irb(main):001:0> 将 RUBY_VERSION 1.8.7
    • @thoeolh:是的。我认为它在 1.9.1 或 1.8.7 中不可用。
    • @thotheloh:start_with?end_with? 在 1.8.7 中都可用。那么你到底尝试了什么?你的字符串的开头或结尾有空格吗?或者可能是尾随换行符?
    • @mu 太短:如果有换行符之类的东西搞砸了,最好的找出方法是在字符串上使用puts string.inspect
    【解决方案2】:

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

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

    这样您就可以验证其他内容,例如标题必须全部大写并且需要在其周围留有空格 (/^\|\s[A-Z]+\s\|$/)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多