我想用空格分割字符串。但是,如果单词用引号引起来,则将它们视为一个单词。
例如要拆分的单词
。我会得到word
,to
,split
.
但是如果
"word to"split
我应该得到 "word to"
,split
。引号保留。
最佳答案
这就是你想要的吗??
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TmpTest {
public static void main(String args[]) {
final String regex = "\".*?\"|\\b\\w+\\b";
final String string = "\"word to\" split i should get \"word to2\", split.";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
}
}
}
关于Java 按条件用空格分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40374370/