java中的正则表达式根据字长

时间:2017-12-11 09:34:12

标签: regex

目前我收到了一个文本文件,我需要根据它们的长度删除一些单词。在这种特殊情况下,我需要删除少于5个字符的单词。 这些是文本文件中的一些行:

"Yellow Submarine"


In the town where I was born
 Lived a man who sailed to sea
 And he told us of his life
In the land of submarines

乍一看,我认为这是一项容易完成的任务,但不幸的是我没有成功。这是我到目前为止所做的:

try{
        FileReader input= new FileReader("sub.txt");
        BufferedReader myBuffer= new BufferedReader(input);
        String c=myBuffer.readLine();
        Pattern p=Pattern.compile("\\s[A-Za-z0-9]{5,}\\s");
        Matcher m;

        while (c!=null){
            if (c!=null){
                m=p.matcher(c);
                if (m.find()){
                    System.out.println(m.group());
                }
            }
        }

    c=myBuffer.readLine();
    } catch (IOException ex) {
        System.out.println("It was not possible to load the file");
    }

是否有关于我定义正则表达式的方法或者可以使用特殊函数?

提前致谢!! :)

1 个答案:

答案 0 :(得分:1)

要删除少于5个字母的字词,您可以使用

line=line.replaceAll("(?U)\\s*\\b\\p{Alnum}{1,4}\\b", "");

.replaceAll将删除与该模式匹配的所有子字符串:

  • (?U) - Pattern.UNICODE_CHARACTER_CLASS内联修饰符选项(嵌入式标记),可使\b\p{Alnum}识别Unicode
  • \\s* - 0+空格(您可能希望使用\\W*来匹配任何0 + nbon-word字符)
  • \\b - 字边界
  • \\p{Alnum}{1,4} - 1到4个字母数字字符
  • \\b - 一个单词边界。