【问题标题】:Using select rather than gsub to avoid multiple regex evaluations in Ruby在 Ruby 中使用 select 而不是 gsub 来避免多次正则表达式评估
【发布时间】:2012-04-24 06:48:36
【问题描述】:

这是一个需要多次正则表达式评估但得到我想做的输出的输出(删除除文本之外的所有内容)。

words = IO.read("file.txt").
gsub(/\s/, ""). # delete white spaces
gsub(".",""). # delete periods
gsub(",",""). # delete commas
gsub("?","") # delete Q marks
puts words
# output
#      WheninthecourseofhumaneventsitbecomesnecessaryIwanttobelieveyoureallyIdobutwhoamItoblameWhenthefactsarecountedthenumberswillbereportedLotsoflaughsCharlieIthinkIheardthatonetentimesbefore

看这篇文章 - Ruby gsub : is there a better way - 我想我会尝试做一个匹配来完成相同的结果,而无需多次正则表达式评估。但我没有得到相同的输出。

words = IO.read("file.txt").
match(/(\w*)+/)
puts words
# output - this only gets the first word
# When

而这只得到第一句话:

words = IO.read("file.txt").
match(/(...*)+/)
puts words

# output - this only gets the first sentence
# When in the course of human events it becomes necessary.

关于在匹配而不是 gsub 上获得相同输出(包括去除空格和非单词字符)的任何建议?

【问题讨论】:

    标签: ruby regex gsub


    【解决方案1】:

    你可以在一个 gsub 操作中做你想做的事:

    s = 'When in the course of human events it becomes necessary.'
    s.gsub /[\s.,?]/, ''
    # => "Wheninthecourseofhumaneventsitbecomesnecessary"
    

    【讨论】:

    • 谢谢赫克。我想我明白了。这将评估任何空白字符 (\s)、句点 (.) 逗号 (,) 或问号 (?) 并将其替换为空字符(因为引号之间没有任何内容)。有帮助。只需要继续努力掌握正则表达式。
    【解决方案2】:

    您不需要为此进行多次正则表达式评估。

    str = "# output - this only gets the first sentence
    # When in the course of human events it becomes necessary."
    p str.gsub(/\W/, "")
    #=>"outputthisonlygetsthefirstsentenceWheninthecourseofhumaneventsitbecomesnecessary"
    

    【讨论】:

    • 知道了。将任何非单词字符 (\W) 替换为空字符 ("")。好的,如实告知。我一定是分析过度了!谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-16
    相关资源
    最近更新 更多