用户正则表达式(取消)匹配高于特定值的所有单词长度



关于Java RegEx的问题:

有一个分词器,我只想返回长度超过一定长度的代币。

例如:我需要返回此文本中超过 1 个字符的所有标记:"这是文字。">

我需要获得 3 个令牌:">这个"、">是"、"文本">不需要以下标记:">a">"."。请注意,字符串可以包含任何字符(不仅是 alpha-bet 字符(

我尝试了这段代码,但我不确定如何完成它:

    String lines[]  = {"This is o n e l e tt e r $ % ! sentence"};

    for(String line : lines)
    {
        String orig = line;
        Pattern Whitespace = Pattern.compile("[\s\p{Zs}]+");
        line = Whitespace.matcher(orig).replaceAll(" ").trim();
        System.out.println("Test:t'" + line + "'");
        Pattern SingleWord = Pattern.compile(".+{1}");  //HOW CAN I DO IT?
        SingleWord.matcher(line).replaceAll(" ").trim();
        System.out.println("Test:t'" + line + "'");

    }

谢谢

为什么不使用这样的w{2,}

String line = "This is o n e l e tt e r $ % ! sentence";
Pattern pattern = Pattern.compile("\w{2,}");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
    System.out.println(matcher.group());
}

输出

This
is
tt
sentence

编辑

然后,您可以使用此[A-Za-z0-9_@.-]{2,}指定不想避免的特殊字符,也可以使用[^s]{2,}S{2,}非空格字符:

输入

This is o email@gmail.com n e l e tt e r $ % ! sentence

输出

This
is
email@gmail.com
tt
sentence

如果你使用Java 8,你可以这样做:

String line = "This is o n e l e tt e r $ % ! sentence";
ArrayList<String> array = new ArrayList<>(Arrays.asList(line.split(" ")));
array.removeIf(u -> u.length() == 1);

array现在包含:

This
is
tt
sentence

我只会使用一些简单的东西,例如

List<String> words = new LinkedList<String>();
Matcher m = Pattern.compile("\S{2,}").matcher(line);
while(m.find())
{
    words.add(m.group(0));
}

\S(大写"s"(匹配所有非空格字符。

免责声明:我没有运行这个,但它应该可以工作(也许需要一些最小的更改(

最新更新