java - split string using regular expression

后端 未结 3 1873
一生所求
一生所求 2020-12-31 23:58

I need to split a string where there\'s a comma, but it depends where the comma is placed.

As an example

consider the following:

C=75,user_is         


        
相关标签:
3条回答
  • 2021-01-01 00:20

    consider using a parser generator for parsing this kind of query. E.g: javacc or antlr

    0 讨论(0)
  • 2021-01-01 00:22

    As an alternative, if you need more than one level of parentheses, you can create a little string parser for parsing the string character by character.

    0 讨论(0)
  • 2021-01-01 00:34

    If you don't have more than one level of parentheses, you could do a split on a comma that isn't followed by a closing ) before an opening (:

    String[] splitArray = subjectString.split(
        "(?x),   # Verbose regex: Match a comma\n" +
        "(?!     # unless it's followed by...\n" +
        " [^(]*  # any number of characters except (\n" +
        " \\)    # and a )\n" +
        ")       # end of lookahead assertion");
    

    Your proposed rule would translate as

    String[] splitArray = subjectString.split(
        "(?x),        # Verbose regex: Match a comma\n" +
        "(?<!\\p{Lu}) # unless it's preceded by an uppercase letter\n" +
        "(?!\\p{Lu})  # or followed by an uppercase letter");
    

    but then you would miss a split in a text like

    Org=NASA,Craft=Shuttle
    
    0 讨论(0)
提交回复
热议问题