简体   繁体   English

在Java中使用多个split参数分割字符串

[英]Splitting a string in java with more than one split parameter

I am working with strings and had a quick question. 我正在使用琴弦,并且有一个快速的问题。 I have a string of text I extracted from a file and now want to create a string array with each sentence of the text, I understand I could use string.split("."); 我有一个从文件中提取的文本字符串,现在想用文本的每个句子创建一个字符串数组,我知道我可以使用string.split("."); for periods but how do I add question marks and exclamation marks. 期间,但如何添加问号和感叹号。 I tried string.split("." + "!" + "?"); 我尝试过string.split("." + "!" + "?"); but that didn't seem to work. 但这似乎不起作用。 Any help would be appreciated! 任何帮助,将不胜感激!

string.split(".") does not work as you expect it does... string.split(".")无法正常工作...

String s = "Hello.world";
System.out.println(Arrays.toString(s.split("."))); // outputs [] 

Split method takes a regex . Split方法使用一个正则表达式

String s = "Hello.world";
System.out.println(Arrays.toString(s.split("\\."))); // outputs [Hello, world]

The regex of ".!?" ".!?"的正则表达式 says "any character followed by zero or more ! " (which effectively is the same result as just "." ) 表示“任何字符后跟零个或多个字符! ”(实际上是与"."相同的结果)

If you want to split on individual characters, use a character class 如果要分割单个字符,请使用字符类

string.split("[.!?]")

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

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