简体   繁体   中英

using regular expression as delimiter with StringTokenizer

I am new to java progrmming and came across the StringTokenizer class. The constructor accepts the string to be split and another optional delimiter string each character of which gets treated as an individual delimiter while splitting the original string. I was wondering if there is any way to split the string passing a regex as the delimiter. for example:

String s="34.5xy32.6y45.7x36xy"
StringTokenizer t=new StringTokenizer(s,"xy");
System.out.println(t.nextToken());
System.out.println(t.nextToken());

The actual output is:

34.5
32.6

However, the desired output is:

34.5
32.6y45.7x36

Hope you guys can help. Also, please suggest some way around if it is not possible with StringTokenizer class.

Thanks in advance.

ps Is there any way to know which character the StringTokenizer is currently using as delimiter out of the provided set?

Here you would want to use String.split() , this will give you an array with your desired output.

It will take your input and split it around exact matches of your string you provide. StringTokenizer will split around anyone of the set that you provide it rather than a regular expression.

So you change your code to:

String s="34.5xy32.6y45.7x36xy";
String[] splitString = s.split("xy");
System.out.println(splitString [0]);
System.out.println(splitString [1]);

For more complex examples you probably want boundary checking on the array also to make you don't go off the end of the array

Try with this.

String s="34.5xy32.6y45.7x36xy";
final String SPLIT_STR = "xy";
final String mainStr = "34.5xy32.6y45.7x36xy";
final String[] splitStr = mainStr.split(SPLIT_STR);
System.out.println("First Index Of xy : " +
mainStr.indexOf(SPLIT_STR));
for(int index=0; index < splitStr.length; index++) {
System.out.println("Split : " + splitStr[index]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM