将代码放在匿名括号中可以节省内存吗?

发布于 2025-01-19 12:28:53 字数 1138 浏览 2 评论 0原文

我是初学者,由于某种原因,我喜欢努力节省记忆。现在,我认为这很有趣。

因此,在这个问题中,我有一个将烤肉串单词匹配的正则态度,后来将它们变成骆驼箱单词,我想知道这是否在给定的字符串中发生了。我尝试了matcher.matches(),但我发现它仅在整个字符串匹配时起作用,因此我只能想到编译正则拨号并使用matcher.find()< /code>将布尔值放入变量中的方法,但我想将所有内容包装在括号中以保存内存。

这是我的解决方案:

String regex = "(?:([\\p{IsAlphabetic}]*)?(-[\\p{IsAlphabetic}]+))+";

boolean hasSubSequence;
{
    Matcher m = Pattern.compile(regex).matcher(identifier);
    hasSubSequence = m.find();
}

if (hasSubSequence) {
    Matcher kebabCaseMatches = Pattern.compile(regex).matcher(identifier);
    while (kebabCaseMatches.find()) {
        String currentOccurence = kebabCaseMatches.group();
        
        while (currentOccurence.contains("-")) {
            currentOccurence = currentOccurence.replaceFirst("-[\\p{IsAlphabetic}]", Character.toString(Character.toUpperCase(currentOccurence.charAt(currentOccurence.indexOf("-") + 1))));
        }
        
        // "identifier" is the function's argument
        identifier = identifier.replaceFirst(regex, currentOccurence);
    }
}

这真的可以节省内存吗?

I'm a beginner and for some reason, I like to make effort to save memory. For now I think it's fun.

So in this problem, I have a regex that matches kebab-case words and later turns them into camel-case words, and I want to know if that is some occurrence in a given string. I tried Matcher.matches() but I found out that it only works if the entire string is matched, so I only could think of compiling the regex and use the Matcher.find() method to put a boolean value inside a variable, but I wanted to enclose everything in brackets to save memory.

This is my solution:

String regex = "(?:([\\p{IsAlphabetic}]*)?(-[\\p{IsAlphabetic}]+))+";

boolean hasSubSequence;
{
    Matcher m = Pattern.compile(regex).matcher(identifier);
    hasSubSequence = m.find();
}

if (hasSubSequence) {
    Matcher kebabCaseMatches = Pattern.compile(regex).matcher(identifier);
    while (kebabCaseMatches.find()) {
        String currentOccurence = kebabCaseMatches.group();
        
        while (currentOccurence.contains("-")) {
            currentOccurence = currentOccurence.replaceFirst("-[\\p{IsAlphabetic}]", Character.toString(Character.toUpperCase(currentOccurence.charAt(currentOccurence.indexOf("-") + 1))));
        }
        
        // "identifier" is the function's argument
        identifier = identifier.replaceFirst(regex, currentOccurence);
    }
}

Does this really save memory?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

Oo萌小芽oO 2025-01-26 12:28:53

您可以在声明regex(静态最终?)的地方编译该模式:将节省速度和许多实例。括号是巫毒。

You could compile the pattern once where you declared regex (static final?): would save speed and many instances. Brackets are voodoo.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文