You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对以全大写字母括号结尾的句子实现标题大小写转换(排除特定单词)

Fixing Title Case Conversion for Sentences Ending with Uppercase Acronyms in Parentheses

Got it, let's break down what's wrong with your original regex and build a solution that does exactly what you need—applying title case to the main text (while leaving small words like for, and, the lowercase) and preserving the uppercase acronym in parentheses.

The Problem with Your Original Regex

Your regex (^[\p{L}\W]+)([(][\p{Lu}]{3,}[)]$) \U\1\2 uses \U to uppercase the entire first capture group. That's why it's turning everything before the parentheses into all caps—\U is a "full uppercase" flag for the entire matched group, not title case.

The Solution: Targeted Title Case with Callback Functions

To get proper title case (capitalize first letter of most words, leave small function words lowercase), we need to:

  1. Identify sentences that end with an uppercase acronym in parentheses.
  2. Split the main text into individual words.
  3. Capitalize words except for specified small words (unless they're the first word).
  4. Reassemble the text with the original acronym intact.

Here's how to implement this in two common languages:

Example 1: Python

Python's re.sub() supports callback functions, which let us handle the title case logic precisely:

import re

# Customize this list with any small words you want to keep lowercase
lowercase_exceptions = {'for', 'and', 'the', 'of', 'in', 'on', 'at', 'to', 'a', 'an'}

def format_title_case(match):
    # Extract the text before the acronym and the acronym itself
    main_text = match.group(1).strip()
    acronym = match.group(2)
    
    # Split into words and apply title case rules
    words = main_text.split()
    transformed_words = []
    for idx, word in enumerate(words):
        # Always capitalize the first word; lowercase exceptions only if not first
        if idx == 0 or word.lower() not in lowercase_exceptions:
            transformed_words.append(word.capitalize())
        else:
            transformed_words.append(word.lower())
    
    # Reassemble the final sentence
    return f"{' '.join(transformed_words)} ({acronym})"

# Test with your example
original = "foundation for economic education (FEE)"
result = re.sub(r'^(.*?)\(([A-Z]{3,})\)$', format_title_case, original)
print(result)  # Output: Foundation for Economic Education (FEE)

Example 2: JavaScript

JavaScript's String.replace() also accepts a callback function for dynamic replacements:

const lowercaseExceptions = new Set(['for', 'and', 'the', 'of', 'in', 'on', 'at', 'to', 'a', 'an']);

function formatTitleCase(match, mainText, acronym) {
    const words = mainText.trim().split(' ');
    const transformedWords = words.map((word, idx) => {
        if (idx === 0 || !lowercaseExceptions.has(word.toLowerCase())) {
            return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
        }
        return word.toLowerCase();
    });
    return `${transformedWords.join(' ')} (${acronym})`;
}

const original = "foundation for economic education (FEE)";
const result = original.replace(/^(.*?)\(([A-Z]{3,})\)$/, formatTitleCase);
console.log(result); // Output: Foundation for Economic Education (FEE)

Key Notes

  • You can adjust the lowercase_exceptions set/list to include any other words you want to keep lowercase (like or, but, etc.).
  • The regex ^(.*?)\(([A-Z]{3,})\)$ safely captures the main text (non-greedily) and the uppercase acronym (3+ letters) at the end of the sentence.
  • This approach ensures you don't accidentally uppercase small function words while still applying proper title case to content words.

内容的提问来源于stack exchange,提问作者Althussa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:29:49