【问题标题】:Split string based on different patterns of a string [duplicate]根据字符串的不同模式拆分字符串[重复]
【发布时间】:2020-09-25 04:01:52
【问题描述】:

我想根据多个字符串模式在字符串中查找子字符串。

例如:"word1 word2 word3 and word4 word5 or word6 in word7 in word8" 根据andorin进行拆分。

输出应该是

word1 word2 word3
and word4 word5
or word6
in word7
in word8

【问题讨论】:

    标签: java regex string substring


    【解决方案1】:

    与此一起使用:

    String str = "word1 word2 word3 and word4 word5 or word6 in word7 in word8";
    
                String[] parts = str.split("and |in |or ");
    
                for(String part : parts)
                    System.out.println(part);
            }
    

    【讨论】:

    • 但是这不会打印它被分割的关键字。
    【解决方案2】:

    您可以使用前瞻来做到这一点,?= 如下所示:

    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            String str = "word1 word2 word3 and word4 word5 or word6 in word7 in word8";
            String[] arr = Arrays.stream(str.split("(?=\\s+and)|(?=\\s+or)|(?=\\s+in)"))
                            .map(String::trim)
                            .toArray(String[]::new);
            // Display
            Arrays.stream(arr).forEach(System.out::println);
        }
    }
    

    输出:

    word1 word2 word3
    and word4 word5
    or word6
    in word7
    in word8
    

    【讨论】:

      猜你喜欢
      • 2011-08-04
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 1970-01-01
      • 2019-09-19
      • 1970-01-01
      相关资源
      最近更新 更多