首页 > 编程知识 正文

java正则表达式详解,java中pattern的用法

时间:2023-05-06 07:37:11 阅读:9034 作者:874

最近的数据分析需要对数据进行分割组合,再分割、清洗以获得所需的数据。 分割数据时,甚至会使用分割方法,分割后可能会发生问题。 例如,分隔字符数组的长度与是否以分隔符结尾不同。

一. java split的简单使用方法

公共类剥离测试{

publicstaticvoidmain (字符串[ ] args ) {

//一般分割

String a='hello world ni hao ';

String[] array1=a.split (' );

system.out.println (阵列1 [0];

system.out.println (array1. length;

}

---------输出-------

你好

4

二是无法识别字符串末尾的分隔符

这个方法很常用也很有用,但是如果空格跟在字符串末尾怎么办? 让我看一下

公共类剥离测试{

publicstaticvoidmain (字符串[ ] args ) {

//一般分割

String a='hello world ni hao ';

String[] array1=a.split (' );

system.out.println (阵列1 [0];

system.out.println (array1. length;

}

}

---------输出---------

你好

4

为什么数组的长度还只有4个? 这是误会之一。 此时的split ) )方法不会识别末尾的字符。 分割后,看源代码有以下几种语言。

thearrayreturnedbythismethodcontainseachsubstringofthisstringthatisterminatedbyanothersubstringthatmatchesthegivenexpressiononor string.thesubstringsinthearrayareintheorderinwhichtheyoccurinthisstring.iftheexpressiondoesnotmatc hanypartoftheinputhethenthenthethethed

如果要拆分的字符串末尾的数据为空,请注意不要使用此方法。 之后,找到了方法split '、-1,如下所示

String a='hello world ni hao ';

String[] array1=a.split (',-1);

system.out.println (阵列1 [0];

system.out.println (array1. length;

-----------输出---------------------------------------。

你好

5

三特殊符号分割

公共类剥离测试{

publicstaticvoidmain (字符串[ ] args ) {

//特殊分割

字符串a=' hello ' world ' ni ';

string[]array1=a.split((|);

system.out.println (阵列1 [0];

system.out.println (array1. length;

}

-------输出--------

19

上面竖线时的特殊符号,用右双斜线翻译后分割,如下所示。

公共类剥离测试{

publicstaticvoidmain (字符串[ ] args ) {

//特殊分割

字符串a=' hello ' world ' ni ';

string[]array1=a.split((| );

system.out.println (阵列1 [0];

system.out.println (array1. length;

}

------输出-------

你好

4

4个自定义split ) )方法在java中拆分长字符串的本机split方法效率低下,需要自己重写split ) )方法。 我自己写的分割方法如下(使用索引关闭)。

公共静态字符串[ ] newsplit (字符串字符串,字符串str split )。

//步骤1计算数组大小

int size=0;

索引=0;

do{

size;

索引;

索引=strinfo.index of (str split,index );

} while (索引!=-1;

String[] arrRtn=new String[size]; //返回数组

-----------------------------请参阅

//步骤2为数组赋值

int startIndex=0;

int endIndex=0;

for(intI=0; i size; I ) {

end index=strinfo.index of (str split,startIndex );

if (结束索引==-1 ) {

arr RTN [ I ]=strinfo.substring (startindex );

} else {

arr RTN [ I ]=strinfo.substring (startindex,endIndex );

}

startIndex=endIndex 1;

}

返回arr RTN;

}

publicstaticvoidmain (字符串[ ] args ) {

//特殊分割

String a='hello|world|ni|hao|';

//string[]array1=a.split(((| );

string[]Array1=Newsplit(a,'|' );

system.out.println (阵列1 [0];

system.out.println (array1. length;

}

---------输出-------

你好

5

此外,由于本机split方法识别正则表达式,因此不识别特殊字符,因此不需要翻译特殊字符

如果radjm需要更高效的split方法,也可以使用stringutils.split(str,'')方法,它比本机split更高效。 此方法来自apache-common的jar包。 我在用

请注意,虽然是commons-lang3-3.0.1.jar软件包,但缺省情况下将省略StringUtils.split (),因为它不识别字符串的开头和结尾分隔符。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。