Splitting on multiple delimiters but keep the delimiters on the same string

后端 未结 3 1607
伪装坚强ぢ
伪装坚强ぢ 2021-01-20 13:44

I want help with regular expressions to solve the following problem:

I have a string such as \"1£23$456$£$\"

when I split on it I want the output in my strin

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

    You probably want this

    Matcher m = Pattern.compile("[^$£]*(\\$|£)").matcher(input);
    
    0 讨论(0)
  • 2021-01-20 14:22

    Use the more powerful Matcher functionality instead of String.split. The below code should work, but has not been optimized:

    Pattern pattern = Pattern.compile("\\d*(\\$|£)");
    
    String input = "1£23$456$£$";
    Matcher matcher = pattern.matcher(input);
    List<String> output = new ArrayList<>();
    while (matcher.find()) {
        output.add(matcher.group());
    }
    

    Printing out output.toString() generates:

    [1£, 23$, 456$, £, $]


    Updated requirements:

    1. Also include delimiter characters: +, -, *, and /
    2. Non-delimiter characters are only digits with optional spaces before the delimiters.
    3. Any such spaces are part of the value, not delimiters themselves.

    Use the regular expression: \\d*\\s*[-\\+\\*/\\$£]

    That pattern, with this given input:

    1£23$456$£$7+89-1011*121314/1 £23 $456 $ £ $7 +89 -1011 * 121314 /

    Will generate this output:

    [1£, 23$, 456$, £, $, 7+, 89-, 1011*, 121314/, 1 £, 23 $, 456 $, £, $, 7 +, 89 -, 1011 *, 121314 /]

    0 讨论(0)
  • 2021-01-20 14:28

    Use a look behind, which is non-consuming:

    String[] parts = str.split("(?<=\\D)");
    

    That's all there is to it. The regex means to split "just after every non-digit", which seems to be exactly your intention.


    Some test code:

    String str = "1£23$456$£$";
    String[] parts = str.split("(?<=\\D)");
    System.out.println( Arrays.toString( parts));
    

    Output:

    [1£, 23$, 456$, £, $]
    
    0 讨论(0)
提交回复
热议问题