簡體   English   中英

Ruby String與正則表達式分開

[英]Ruby String split with regex

這是Ruby 1.8.7但應該與1.9.x相同

我試圖拆分一個字符串,例如:

a = "foo.bar.size.split('.').last"
# trying to split into ["foo", "bar","split('.')","last"]

基本上在它代表的命令中拆分它,我試圖用Regexp做但不確定如何,想法是使用regexp

a.split(/[a-z\(\)](\.)[a-z\(\)]/)

在這里嘗試使用組(\\.)來分割它,但這似乎不是一個好方法。

我認為這樣做會:

a.split(/\.(?=[\w])/)

我不知道你對正則表達式了解多少,但是(?=[\\w])是一個前瞻,說“如果下一個字符是一個字母的字符,則只匹配點”。 預測實際上不會抓取它匹配的文本。 它只是“看起來”。 所以結果正是你想要的:

> a.split(/\.(?=[\w])/)
 => ["foo", "bar", "size", "split('.')", "last"] 

我擔心正則表達式不會帶你走得太遠。 考慮以下表達式(也是有效的Ruby)

"(foo.bar.size.split( '.' )).last"
"(foo.bar.size.split '.').last"
"(foo.bar.size.split '( . ) . .(). .').last"

問題是,調用列表實際上是一個調用樹。 最簡單的解決方案可能是使用Ruby解析器並根據您的需要轉換解析樹(在此示例中,我們遞歸地下降到調用樹中,將調用收集到列表中):

# gem install ruby_parser
# gem install awesome_print
require 'ruby_parser'
require 'ap'

def calls_as_list code
    tree = RubyParser.new.parse(code)

    t = tree
    calls = []

    while t
        # gather arguments if present
        args = nil
        if t[3][0] == :arglist
            args = t[3][1..-1].to_a
        end
        # append all information to our list
        calls << [t[2].to_s, args]
        # descend to next call
        t = t[1]
    end

    calls.reverse
end

p calls_as_list "foo.bar.size.split('.').last"
#=> [["foo", []], ["bar", []], ["size", []], ["split", [[:str, "."]]], ["last", []]]
p calls_as_list "puts 3, 4"
#=> [["puts", [[:lit, 3], [:lit, 4]]]]

並顯示任何輸入的解析樹:

ap RubyParser.new.parse("puts 3, 4")
a = "foo.bar.size.split('.').last"
p a.split(/(?<!')\.(?!')/)

#=> ["foo", "bar", "size", "split('.')", "last"]

您正在尋找Lookahead和Lookbehind斷言。 http://www.regular-expressions.info/lookaround.html

在這里,我沒有紅寶石環境。 我嘗試使用python re.split()。

In : re.split("(?<!')\.(?!')",a)
Out: ['foo', 'bar', 'size', "split('.')", 'last']

上面的正則表達式具有負前瞻和后觀,以確保只有單引號之間的“點”不能作為分隔符。

當然,對於你給出的例子,一個lookbehind或lookahead就足夠了。 您可以根據自己的要求選擇正確的方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM