java 正则表达式 : capitalize words with certain number of characters

标签 java regex string character

我正在尝试将字符串中超过 5 个字符的单词大写。

我能够使用 .length 检索大于 5 个字符的单词数,并且可以排除大于 5 个字符的单词,但无法将它们大写。

例如。输入:“我喜欢吃馅饼”

例如。输出:“我喜欢吃馅饼”

这是我的代码:

 public static void main(String[] args) {
    String sentence = "";
    Scanner input = new Scanner(System.in);

    System.out.println("Enter a sentence: ");
    sentence = input.nextLine();
    String[] myString = sentence.split("\\s\\w{6,}".toUpperCase());
     for (String myStrings : myString) {
         System.out.println(sentence);
         System.out.println(myStrings);
         }

最佳答案

String sentence = "";
StringBuilder sb = new StringBuilder(sentence.length());
Scanner input = new Scanner(System.in);

System.out.println("Enter a sentence: ");
sentence = input.nextLine();
/*
 * \\s (match whitespace character)
 * (<?g1> (named group with name g1)
 * \\w{6,}) (match word of length 6) (end of g1)
 * | (or)
 * (?<g2> (named group with name g2)
 * \\S+) (match any non-whitespace characters) (end of g2)
 */
Pattern pattern = Pattern.compile("\\s(?<g1>\\w{6,})|(?<g2>\\S+)");
Matcher matcher = pattern.matcher(sentence);

//check if the matcher found a match
while (matcher.find())
{
    //get value from g1 group (null if not found)
    String g1 = matcher.group("g1");
    //get value from g2 group (null if not found)
    String g2 = matcher.group("g2");

    //if g1 is not null and is not an empty string
    if (g1 != null && g1.length() > 0)
    {
        //get the first character of this word and upercase it then append it to the StringBuilder
        sb.append(Character.toUpperCase(g1.charAt(0)));
        //sanity check to stop us from getting IndexOutOfBoundsException
        //check if g1 length is more than 1 and append the rest of the word to the StringBuilder
        if(g1.length() > 1) sb.append(g1.substring(1, g1.length()));
        //append a space
        sb.append(" ");
    }
    //we only need to check if g2 is not null here
    if (g2 != null)
    {
        //g2 is smaller than 5 characters so just append it to the StringBuilder
        sb.append(g2);
        //append a space
        sb.append(" ");
    }
}
System.out.println("Original Sentence: " + sentence);
System.out.println("Modified Sentence: " + sb.toString());

关于java 正则表达式 : capitalize words with certain number of characters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30671722/

相关文章:

java - ANTLR4语法无法涵盖所有​​情况

regex - .htaccess 重写除特定 http_host 之外的任何内容的规则

string - 给定长度 L 找到仅由 as & bs >= L 组成的最短字符串,这样添加一些字符(a 或 b)不会产生新的回文

java - 如何将字符串一分为二并将其存储在字段中

android - 使用对字符串资源的引用作为其他资源的名称属性

java - 如何创建 CL GL 互操作上下文?

java - 不断检查子弹是否触及节点

regex - 正则表达式从nuget包文件名中解析包名称和版本号

java - 如何将所有偶数移动到数组的前面?

java - 正则表达式替换一个字符或仅替换一个重复的字符