How to use comma and dot as delimiter in addition with Java default delimiter

怎甘沉沦 提交于 2020-01-11 06:26:32

问题


I have a text file which contains lot of permutations and combinations of special characters, white space and data. I am storing the content of this file into an array list, and if i am not using useDelimiter() function, Java is reading my text perfectly.

The only issue is that its not accepting comma (,) and dot (.) as delimiter.

I know I can use input.useDelimiter(",|.| |\n") to use comma , dot, space as delimiter and others options as well, but then the results I get are not correct as java gives me now.

Is there a way to instruct java to use comma and dot as delimiters along with whatever default delimiter it uses?

Thanks in advance for your help :)

Regards, Rahul


回答1:


The default delimiter for Scanner is defined as the pattern \p{javaWhitespace}+, so if you want to also treat comma and dot as a delimiter, try

input.useDelimiter("(\\p{javaWhitespace}|\\.|,)+");

Note you need to escape dot, as that is a special character in regular expressions.




回答2:


Use escaped character like this:

input.useDelimiter("\\.");



回答3:


You could do this:

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

Basically the .split() method will split the string according to (in this case) delimiter you are passing and will return an array of strings.

However, you seem to be after a List of Strings rather than an array, so the array must be turned into a list by using the Arrays.asList() utility. Just as an FYI you could also do something like so:

String str = "...";
ArrayList<String> List = Arrays.asList(str.split(","));


来源:https://stackoverflow.com/questions/36884025/how-to-use-comma-and-dot-as-delimiter-in-addition-with-java-default-delimiter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!