【发布时间】:2013-04-06 18:44:21
【问题描述】:
请在不使用正则表达式的情况下进行数组和文件内容之间的匹配。
请重播:-
如果我有一个包含以下句子的 txt 文件:
the sql is the best book for jon.
book sql is the best title for jon.
the html for author asr.
book java for famous writer amr.
如果我将此字符串存储在数组中;
sql html java
jon asr amr
我想在文件中搜索数组的内容,例如如果“sql”和“jon”在txt文件中的同一个句子中,然后写句子和
将“sql”之前的所有单词命名为prefix,并将两个“sql”和“jon”之间的所有单词命名为middle,以及“jon”之后的所有单词命名为后缀。
我尝试写 cod:
String book[][] = {{"sql","html","java"},{"jon","asr","amr"}};
String input;
try {
BufferedReader br = new BufferedReader(new FileReader(new File("sample.txt") ));
input= br.readLine();
while ((input)!= null)
{
if((book[0][0].contains(input))&( book[1][0]).contains(input)){
System.out.println();
if((book[0][1].contains(input))&( book[1][1]).contains(input)){
System.out.println();
if((book[0][2].contains(input))&( book[1][2]).contains(input)){
System.out.println();
}
else
System.out.println("not match");
}}
}} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我不知道如何编写代码来提取前缀、中间和后缀
输出是:
the sentence is : the sql is the best book for jon.
prefix is :the
middle is:is the best book for
suffix is: null
等等……
【问题讨论】:
-
你的代码的输出是什么?
-
您可以使用 java 中的 Pattern 和 Matcher。链接:docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html 和 docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html。您将需要在程序中编译一个正则表达式模式并找到匹配的字符串。然后使用
appendReplacement执行剩下的任务。这应该相当容易。其他方法可以是从数组到文本中查找匹配查询字符串的索引,然后将子字符串打印为前缀、中间和后缀的输出。
标签: java string multidimensional-array