java中的正则表达式及其与indexOf相比的性能 [英] Regex in java and its performance compared to indexOf
问题描述
请有人告诉我如何匹配_"和句号."使用正则表达式在字符串中仅一次,使用 indexOf() 而不是正则表达式更有效.
Please can someone tell me how to match "_" and a period "." excatly one time in a string using regex, Also is it more efficient using indexOf() instead of regex expression.
String s= "Hello_Wor.ld" or
s="12323_!£££$.asdfasd"
基本上任何字符都可以在_
和之前和之后出现.
唯一的要求是整个字符串应该只包含一次_代码>和<代码>.代码>
bascially any no of characters can come before and after _
and .
the only requirement is that the entire string should only contain one occurance of _
and .
推荐答案
indexOf
将比正则表达式快得多,也可能更容易理解.
indexOf
will be much quicker than a regex, and will probably also be easier to understand.
只测试是否 indexOf('_') >= 0
,然后如果 indexOf('_', indexOfFirstUnderScore) <0
.对这段时间做同样的事情.
Just test if indexOf('_') >= 0
, and then if indexOf('_', indexOfFirstUnderScore) < 0
. Do the same for the period.
private boolean containsOneAndOnlyOne(String s, char c) {
int firstIndex = s.indexOf(c);
if (firstIndex < 0) {
return false;
}
int secondIndex = s.indexOf(c, firstIndex + 1);
return secondIndex < 0;
}
这篇关于java中的正则表达式及其与indexOf相比的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!