V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
79lawyer

想请教一个正则相关问题

  •  
  •   79lawyer · Jul 19, 2021 · 1231 views
    This topic created in 1742 days ago, the information mentioned may be changed or developed.
    字符串"水果,蔬菜,肉类,水产(大闸蟹,小龙虾),鲜花", 怎么用正则匹配出["水果", "蔬菜", "肉类", "水产(大闸蟹,小龙虾)", "鲜花"]的结果呢?谢谢大佬们。
    3 replies    2021-07-20 16:00:43 +08:00
    netwjx
        1
    netwjx  
       Jul 19, 2021   ❤️ 1
    低配版: (?:^|,)([^,]+)
    后续自行 filter 一次 "(大闸蟹,小龙虾)" 的匹配

    高配版: 需要你的正则库支持平衡组
    https://blog.csdn.net/zm2714/article/details/7946437
    0ZXYDDu796nVCFxq
        2
    0ZXYDDu796nVCFxq  
       Jul 19, 2021   ❤️ 1
    这个不应该用正则来做
    写个函数,设置一个空数组,一个索引初始值=0,一个 int=0
    遍历字符串
    遇到'(',int += 1,遇到')',int -= 1
    遇到','并且 int == 0 把 str[索引:当前位置] append 到数组,更新索引

    这个远比正则的可维护性高得多
    可能,你下次还会有更多正则问题
    netwjx
        3
    netwjx  
       Jul 20, 2021
    @gstqc 状态机 ^_^
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1086 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 23:31 · PVG 07:31 · LAX 16:31 · JFK 19:31
    ♥ Do have faith in what you're doing.