用满足特定条件的元素填充子数组-java
我有一个字符串数组,如:用满足特定条件的元素填充子数组-java,java,regex,string,Java,Regex,String,我有一个字符串数组,如: String FileContent = "2017-04-03, 11:25, 2; 2017-04-02, 11:30, 8; 2017-04-03, 14:42, 9"; 我想做的是提取满足特定条件的元素,比如我们需要选择给定日期的数组成员 String[] SplittedContent = FileContent.split("\\s*;\\s*"); String date= "2017-04-03"; for (int i = 0; i < S
String FileContent = "2017-04-03, 11:25, 2; 2017-04-02, 11:30, 8; 2017-04-03, 14:42, 9";
我想做的是提取满足特定条件的元素,比如我们需要选择给定日期的数组成员
String[] SplittedContent = FileContent.split("\\s*;\\s*");
String date= "2017-04-03";
for (int i = 0; i < SplittedContent.length; i++)
if (SplittedContent[i].contains(date))
{
String [] MatchingContent = null;
MatchingContent[i]= SplittedContent[i];
}
String[]SplittedContent=FileContent.split(\\s*;\\s*);
字符串日期=“2017-04-03”;
for(int i=0;i
这一行给了我一个错误:MatchingContent[i]=SplittedContent[i];
有人能帮忙吗?您正试图访问数组中的第i个元素,该元素为空。您需要初始化一个新列表,然后向其中添加项目:
String FileContent = "2017-04-03, 11:25, 2; 2017-04-02, 11:30, 8; 2017-04-03, 14:42, 9";
String date= "2017-04-03";
String[] SplittedContent = FileContent.split("\\s*;\\s*");
List<String> MatchingContent = new ArrayList<>();
for (int i = 0; i < SplittedContent.length; i++)
if (SplittedContent[i].contains(date))
{
MatchingContent.add(SplittedContent[i]);
}
System.out.println(MatchingContent);
// => [2017-04-03, 11:25, 2, 2017-04-03, 14:42, 9]
收集匹配项的另一种方法是使用正则表达式直接匹配所需的子字符串:
String FileContent = "2017-04-03, 11:25, 2; 2017-04-02, 11:30, 8; 2017-04-03, 14:42, 9";
String date= "2017-04-03";
List<String> MatchingContent = new ArrayList<>();
Matcher m = Pattern.compile(date + "[^;]+").matcher(FileContent);
while(m.find()) {
MatchingContent.add(m.group());
}
System.out.println(MatchingContent);
// => [2017-04-03, 11:25, 2, 2017-04-03, 14:42, 9]
stringfilecontent=“2017-04-0311:25,2;2017-04-0211:30,8;2017-04-0314:42,9”;
字符串日期=“2017-04-03”;
List MatchingContent=new ArrayList();
Matcher m=Pattern.compile(日期+“[^;]+”).Matcher(文件内容);
while(m.find()){
MatchingContent.add(m.group());
}
系统输出打印项次(匹配内容);
// => [2017-04-03, 11:25, 2, 2017-04-03, 14:42, 9]
看
[^;]+
否定字符类([^…]
)匹配除以外的任何1+字符代码>替换字符串[]匹配内容=null代码>与列表匹配content=new ArrayList()然后使用MatchingContent.add(SplittedContent[i])代码>
String FileContent = "2017-04-03, 11:25, 2; 2017-04-02, 11:30, 8; 2017-04-03, 14:42, 9";
String date= "2017-04-03";
List<String> MatchingContent = new ArrayList<>();
Matcher m = Pattern.compile(date + "[^;]+").matcher(FileContent);
while(m.find()) {
MatchingContent.add(m.group());
}
System.out.println(MatchingContent);
// => [2017-04-03, 11:25, 2, 2017-04-03, 14:42, 9]