将代码放在匿名括号中可以节省内存吗?
我是初学者,由于某种原因,我喜欢努力节省记忆。现在,我认为这很有趣。
因此,在这个问题中,我有一个将烤肉串单词匹配的正则态度,后来将它们变成骆驼箱单词,我想知道这是否在给定的字符串中发生了。我尝试了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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在声明
regex
(静态最终?)的地方编译该模式:将节省速度和许多实例。括号是巫毒。You could compile the pattern once where you declared
regex
(static final?): would save speed and many instances. Brackets are voodoo.