gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:09:15 25 4
gpt4 key购买 nike

我是在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com