我试图从标点符号中删除一个单词:
例如,如果单词是" 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);
我被困住了,我无法看到另一种做法。
提前致谢
答案 0 :(得分:3)
答案 1 :(得分:1)
除了其他建议,您还可以使用'单词边界'匹配器'\ 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
。
答案 2 :(得分:0)
我认为您可以使用以下正则表达式。但没试过。试试看。
input.split("[\\p{P}]")
答案 3 :(得分:0)
你可以在这里使用子字符串。像这样:
String inWord = "hello?";
String word = inWord.substring (0, 5);
String punctuation = inWord.substring (5, inWord.length ());
System.out.println (word);
System.out.println (punctuation);