Regular Expression to Split String based on space and matching quotes in java

后端 未结 3 681
一整个雨季
一整个雨季 2021-01-27 18:54

I have a String which i need to split based on the space and the exact matching quotes.

If the

string = \"It is fun \\\"to write\\\" regular\\\"expressi         


        
3条回答
  •  时光说笑
    2021-01-27 19:31

    The trick is to use a flexible look ahead to assert that:

    • if there's an even number of quotes in the input, there should be an even number following the space, because an odd number means the space is within quotes
    • if there's an odd number of quotes in the input, there should be an odd number following the space, because an even number means the space is within quotes

    I got it into one line, but it's a whopper:

    String[] parts = str.split("(\\s+|(?

    This correctly splits the example string with or without the trailing quote (whether or not the trailing term includes a space).

提交回复
热议问题