[英]Splitting a string into two
我正在尝试从标点符号中拆分一个单词:
例如,如果单词是“ Hello?”。 我想将“ Hello”存储在一个变量中,并将“?”存储在 在另一个变量中。
我尝试使用.split方法,但是删除了定界符(标点符号),这意味着您将不会保留标点符号。
String inWord = "hello?";
String word;
String punctuation = null;
if (inWord.contains(","+"?"+"."+"!"+";")) {
String parts[] = inWord.split("\\," + "\\?" + "\\." + "\\!" + "\\;");
word = parts[0];
punctuation = parts[1];
} else {
word = inWord;
}
System.out.println(word);
System.out.println(punctuation);
我被困住了,看不到另一种方法。
提前致谢
除了其他建议,您还可以使用“单词边界”匹配器“ \\ b”。 这可能并不总是与您要查找的内容匹配,它会检测到单词和非单词之间的边界,如记录所示: http : //docs.oracle.com/javase/7/docs/api/java/util/regex /Pattern.html
在您的示例中,它起作用了,尽管数组中的第一个元素将是一个空白字符串。
这是一些工作代码:
String inWord = "hello?";
String word;
String punctuation = null;
if (inWord.matches(".*[,?.!;].*")) {
String parts[] = inWord.split("\\b");
word = parts[1];
punctuation = parts[2];
System.out.println(parts.length);
} else {
word = inWord;
}
System.out.println(word);
System.out.println(punctuation);
您可以看到它在这里运行: http : //ideone.com/3GmgqD
我还修复了.contains
改用.matches
。
我认为您可以使用以下正则表达式。 但是没有尝试过。 试试看。
input.split("[\\p{P}]")
您可以在此处使用子字符串。 像这样:
String inWord = "hello?";
String word = inWord.substring (0, 5);
String punctuation = inWord.substring (5, inWord.length ());
System.out.println (word);
System.out.println (punctuation);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.