简体   繁体   English

如何在java中按空格和点分割

[英]How to split by space and dot in java

I have many text like ' J.Depp is an American actor.'我有很多文字,比如“ J.Depp是一位美国演员”。 How can i split where J.Depp like " J. Depp" I write some code but it doesn't work我怎样才能像“ J. Depp”那样拆分J.Depp我写了一些代码但它不起作用

list.forEach(it -> {
        String[] s = it.split(" ");
        for (String temp : s) {
            if (temp.contains(".")) {
                String[] temp2 = temp.split(".");
               // 
            }
        }
        list2.add(s + " .");
    });

split takes a regexp, and . split 需要一个正则表达式,并且 . has special meaning.有特别的意义。 I suggest:我建议:

temp.split(Pattern.quote("."));

This way you can split on whatever you want.通过这种方式,您可以根据需要拆分任何内容。 (Just temp.split("\\\\.") would also work, but the pattern quote variant is more readable and works for anything you care to split on, hence why you should write it that way. (只是temp.split("\\\\.")也可以,但模式引用变体更具可读性并且适用于您想要拆分的任何内容,因此为什么您应该这样写。

String.replaceAll() will do the trick String.replaceAll()可以解决问题

temp.replaceAll("\\.", ". ");

To skip dots which already have the whitespace you may use non-capturing negative lookahead:要跳过已经有空格的点,您可以使用非捕获负前瞻:

temp.replaceAll("\\.(?!\\s)", ". ");

See also Pattern reference.另请参阅Pattern参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM