[英]More efficient way splitting than this?
Is there a more efficient way of splitting a string than this? 有没有比这更有效的分割字符串的方法了?
String input = "=example>";
String[] split = input.split("=");
String[] split1 = split[1].split(">");
String result = split1[0];
The result would be "example". 结果将是“示例”。
Do you really need regex. 您是否真的需要正则表达式。 You can do:
你可以做:
String result = input.substring(1, input.length()-1);
Otherwise if you really have a case for regex then use character class : 否则,如果您确实有正则表达式的情况,请使用character class :
String result = input.replaceAll("[=>]", "");
如果您只想从中获取示例,请执行以下操作:
input.substring(1, input.lastIndexOf(">"))
如果您的string
始终为常量格式,请使用子字符串,否则请使用regex
result = result.substring(1, result.length() - 1);
You can do it more elegant with RegEx groups: 您可以使用RegEx组使其更加优雅:
String sourceString = "=example>";
// When matching, we can "mark" a part of the matched pattern with parentheses...
String patternString = "=(.*?)>";
Pattern p = Pattern.compile(patternString);
Matcher m = p.matcher(sourceString);
m.find();
// ... and access it later
String result = m.group(1);
You can try this regex: ".*?((?:[az][az]+))"
您可以尝试以下正则表达式:
".*?((?:[az][az]+))"
But it would be better when you use something like this: 但是,当您使用以下内容时会更好:
String result = input.substring(1, input.length()-1);
尝试这个
String result = input.replace("[\\W]", "")
You can try this too 你也可以尝试
String input = "=example>";
System.out.println(input.replaceAll("[^\\p{L}\\p{Nd}]", ""));
This will remove all non-words characters 这将删除所有非单词字符
Regex可以完美地完成这项工作,但是只要为将来的解决方案添加新功能,您还可以使用第三方库(例如Google的Guava),它为您的项目添加了许多功能,并且Splitter确实有助于解决类似您的问题有。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.