简体   繁体   English

比这更有效的方式拆分?

[英]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". 结果将是“示例”。

String result = input.replaceAll("[=>]", "");

Very simple regex! 非常简单的正则表达式!

To learn more, go to this link: here 要了解更多信息,请转到此链接: 此处

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.

相关问题 有没有比AffineTransform更有效的方法来旋转Java中的图像? - Is there a more efficient way to rotate images in Java than AffineTransform? 有没有比使用Period / PeriodFormat更有效的方式来获取格式化的字符串? - Is there a more efficient way to get formatted string than with Period/PeriodFormat? 是否有一种更有效的方法来处理按钮单击事件而不是几个if语句? - Is there a more efficient way to handle button click events than several if statements? 有没有比这更有效的方法来引用带有字符串的 int 数组 - Is there a more efficient way to reference an int array with a string than this 将子查询拆分为单独的查询更有效吗? - Splitting Subqueries into Seperate Queries is more efficient? StringTokenizer在JAVA中拆分字符串是否更有效? - Is StringTokenizer more efficient in splitting strings in JAVA? 比 Box 更高效的布局 - more efficient layout than Box “LIKE?”比LIKE'%'||更有效?||'%' - Is “LIKE ?” More efficient than LIKE '%'||?||'%' 在Java中分割String的最有效方法 - Most efficient way of splitting String in Java 在多个符号上拆分java中的字符串 - Splitting a string in java on more than one symbol
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM