Java正则表达式设置最小字符数

标签 java regex

我是在 java 中使用正则表达式的新手,现在在使正则表达式工作时遇到问题。
我想在字符串中保留至少3个字符,如果只有2个字符,我想删除它。

这是我的字符串:

It might be more sensible for real users if I also included a lower limit on the number of letters.

我想要的输出:

might more sensible for real users also includedlower limit the number letters.

所以,我做了一些谷歌搜索,但仍然不起作用。 所以基本上这是完整的代码(1-5是我尝试过的正则表达式):

String input = "It might be more sensible for real users if I also included a lower limit on the number of letters.";
    //1. /^[a-zA-Z]{3,}$/
    //2. /^[a-zA-Z]{3,30}$/
    //3. \\b[a-zA-Z]{4,30}\\b
    //4.  ^\\W*(?:\\w+\\b\\W*){3,30}$
    //5. [+]?(?:[a-zA-Z]\\s*){3,30}

    String output = input.replaceAll("/^[a-zA-Z]{3,}$/", ""); 
    System.out.println(output);

最佳答案

你可以试试这个:

package com.stackoverflow.answer;

public class RegexTest {

    public static void main(String[] args) {
        String input = "It might be more sensible for real users if I also included a lower limit on the number of letters.";
        System.out.println("BEFORE: " + input);
        input = input.replaceAll("\\b[\\w']{1,2}\\b", "").replaceAll("\\s{2,}", " ");
        System.out.println("AFTER: " + input);
    }

}

关于Java正则表达式设置最小字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33973283/

相关文章:

java - 如何使用 Hibernate session 提交非 session 对象

java - @Autowired bean 在 Controller 上与@Valid 一起工作,但在 CRUD 存储库上失败

php - 寻找某个空白区域?

java - 正则表达式查找特殊字符之间的子字符串

javascript - 针对 RegExp 的 Google Closure 编译器警告

java - Eclipse AST Java 模型 : Where in ICompilationUnit stored whether it is class, 接口(interface)或枚举?

java - Spring方法获取给定类型的所有bean

java - Butterknife 无法使用示例

Java 正则表达式匹配器验证

javascript - 匹配字符串的起始字符