【问题标题】:Eiffel: regular expressions how to do grouping埃菲尔:正则表达式如何进行分组
【发布时间】:2019-07-23 20:57:32
【问题描述】:

我想用 eiffel 对正则表达式进行分组。我该怎么做类似的事情

l_reg.compile ("^([0-9]{3}) (rabbit[0-9]).*")
l_groups := l_reg.groups ("123 rabbit1")
my_first_rabbit := l_groups.at (2)

没有找到关于群组、LX_DFA_REGULAR_EXPRESSION 类和其他谷歌搜索的任何示例

【问题讨论】:

    标签: eiffel


    【解决方案1】:

    一种解决方案是使用RX_PCRE_REGULAR_EXPRESSION 而不是LX_DFA_REGULAR_EXPRESSION

    包括$ISE_LIBRARY\contrib\library\gobo\library\regexp\src\library.ecf

    l_reg: RX_PCRE_REGULAR_EXPRESSION
    ...
    l_reg.compile ("^([0-9]{3}) (rabbit[0-9]).*")
    l_reg.match ("123 rabbit1")
    my_first_rabbit := l_reg.captured_substring (2)
    

    没有groups 例程,尽管它可以通过在内部调用captured_substring 来实现。只有一个例程split 做相反的事情:返回与正则表达式不匹配的子字符串。

    类似

        regex_groups (a_haystack, a_needle: STRING): ARRAY[STRING]
                -- Test with https://www.regextester.com/1911
            require
                regex_match (a_haystack, a_needle)
            local
                l_reg: RX_PCRE_REGULAR_EXPRESSION
                l_index: like {RX_PCRE_REGULAR_EXPRESSION}.match_count
            do
                create Result.make_empty
                create l_reg.make
                l_reg.compile (a_needle)
                if l_reg.is_compiled then
                    l_reg.match (a_haystack)
                    from
                        l_index := 1
                    until
                        l_index > l_reg.match_count
                    loop
                        Result.extend (l_reg.captured_substring (l_index))
                        l_index := l_index + 1
                    end
                else
                    --- error compiling regex
                    fallible.set_last_error (create {SIT_INTERNAL_ERROR}.make ("regex_group-> regex does not compile:" + a_needle))
                end
            ensure
                not fallible.has_error
                instance_free: Class
            end
    

    你可以在这里测试你的正则表达式:https://www.regextester.com/1911

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 2020-10-08
    • 2018-12-11
    相关资源
    最近更新 更多