简体   繁体   中英

Split String using scanner or regular expression java

I have a string like follow:

AddStudent,addingToListAddStudent,FD,M,fdsq,fdsq,85/26/9541,fdsq,842-568 523,fdqs,fdqs,fdsq,fdsq,4,MAT101,Math 101,Mr. Smith,20,3.15,1,Computer Science Bsc,120

(all in one line)

I would like to get rid of the "AddStuent,addingToListAddStudent". My problem is that the string can vary in size. I can have more elements separated by commas. I looked into using reuglare expression but I can't get it to work. I tired using this regular expression but I'm not sure how to use it:

/([^,]+)/

Solution

I've used Tom's answer easy, fast and clean, since my string is always going to have the same 2 first elements. So I used this:

string.replace("AddStudent,addingToListAddStudent,", "");

What is the most conventional way of doing it ? using string replace or the regular expression ?

If you want to split the string(As your question title suggests). Use string.split(","), this will return an array of strings ex: {"AddStudent" , "addingToListAddStudent" , ...}

Then you can convert it to a list:

List<String> strings = Arrays.asList(string.split(","));

And then you can remove the first and second elements.

Otherwise, if you only want to remove AddStudent,addingToListAddStudent then use

string.replace("AddStudent,addingToListAddStudent,", "");

If you are not doing it very often you can use String.replace() else if you are using it very often you should compile a regex for it and replace it by the regex. It is much more performant

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