删除java中的标点符号

时间:2015-11-06 02:42:43

标签: java

我是java的初学者,我需要帮助从用户处获取后将单词转换为小写,并在将其作为单词返回之前从标记中删除所有标点符号。标点符号是指不是字母或连字符的任何内容。请注意,标点符号可以出现在字母之前和之后(例如,这是"一个例子,"显示这种情况)。在这个例子中,它应该返回单词this,is,an,example,which,shows,this,occurrence。谢谢!

3 个答案:

答案 0 :(得分:0)

制作小写

string.toLowerCase()

您可以使用正则表达式将所有标点字符替换为空格

免责声明:此代码使用Perl进行测试,并使用短划线替换空格,而不是用空格替换标点符号(因此从技术上讲,它未经测试)。但是,根据this site\p{Punct}应匹配所有标点符号。

Pattern p = Pattern.compile("\p{Punct}");
Matcher m = p.matcher(string);
string = m.replaceAll(" ");
String words[] = string.split(" "); //if you need it

答案 1 :(得分:0)

这是您的问题的一个很好的答案: Efficiently removing specific characters (some punctuation) from Strings in Java?

另外,如果您需要拆分单词,可以使用guava splitters

答案 2 :(得分:0)

使用replaceAll删除字符很简单。你只需要编写一个适合你需要的正则表达式。

public class Main {

    public static void main(String[] args) throws Exception {
        String sentence = "Hi! I'm a sentence with (some) Punctuation.";
        String reduced = sentence.toLowerCase().replaceAll("[^\\s\\w]", "");
        System.out.println(reduced);
    }
}

这会打印hi im a sentence with some punctuation。如果您需要不同的替换,只需将正则表达式替换为另一个,请参阅http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html