[英]Seperate Lines of words and store into array
我有一个txt文件的脚本,我想存储到一个数组列表中
输出只能包含%和数字:
jump 1500
walk 50%
jump 1280
我想将它们存储在数组中
string[] arr = {"jump", "1500"};
并将每个数组添加到列表中,
如何将每一行分成一个数组并忽略不符合第二部分格式的行(仅限%和数字)
将线拆分为数组:
List<String> list = new ArrayList<>();
// for each line ...
// line is "jump 1500" for example
String[] array = line.split(" ");
list.add(array);
// array => {"jump", "1500"}
要检查String ONLY是否包含数字和%,请使用正则表达式:
String line = "1500%";
if (line.matches("^[\\d\\%]*$") {
// match!
}
正则表达式基本上意味着字符串以开头,结尾和仅包含数字或%。 请注意,空字符串将匹配,如果要强制最小长度为1,请使用+而不是*:
"^[\\d\\%]+$"
也许你可以尝试使用Regex实现这一目标。
List saveList = new ArrayList();//List you want to keep result
String pattern = "[\\w]* (\\d*|\\d*%)";
String lineText = "jump 1280";//line text from your txt file
if (lineText.matches(pattern)) {
saveList.add(lineText.split(" "));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.