Java 找到一个字符串并返回它后面的单词

Java 找到一个字符串并返回它后面的单词,java,Java,我有一个方法,它接收参数pdfText(解析后包含pdf文件文本的字符串)和fileName,fileName是我要在其中写入文本的文件 但是现在我需要在本文中找到单词“Keywords”,并只提取它后面的单词,它们在同一行中(直到换行符) 例如,我有一个文本包含以下行 标题:某物 “关键词:计算机、机器人、课程” 标签:标签1,标签2,标签3 结果应该是以下列表[“计算机”、“机器人”、“课程”]。 已解决的问题 所以我一直在寻找如何解决我的问题。这里有一个解决方案,不是很聪明,但很有效:

我有一个方法,它接收参数pdfText(解析后包含pdf文件文本的字符串)和fileName,fileName是我要在其中写入文本的文件

但是现在我需要在本文中找到单词“Keywords”,并只提取它后面的单词,它们在同一行中(直到换行符)

例如,我有一个文本包含以下行

标题:某物

“关键词:计算机、机器人、课程”

标签:标签1,标签2,标签3

结果应该是以下列表[“计算机”、“机器人”、“课程”]。

已解决的问题

所以我一直在寻找如何解决我的问题。这里有一个解决方案,不是很聪明,但很有效:

            //index of first appearence of the word 
            int index = pdfText.indexOf("Keywords");

            //string from that to the end
            String subStr = pdfText.substring(index);


            //index of first appearence of the new line in the new string
            int index1 = subStr.indexOf("\n");


            //the string we need
            String theString = subStr.substring(9,index1); 

            System.out.println(theString);

            //write in the file..use true as parameter for appending text,not overwrite it
            FileWriter pw = new FileWriter(fileName,true);
            pw.write(theString);

            pw.close();

老实说,这个问题太具体了。不管:)

写入文件

String pdfText = "pdfText";
String fileLocation = "fileLocation";
Writer writer = null;
try {
    writer = new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream(fileLocation), "utf-8"));
    writer.write(pdfText);     // String you want to write (i.e. pdfText)
} catch (IOException ioe) {
    ioe.printStackTrace();
} finally {
    try {writer.close();} catch (Exception ex) { ex.printStackTrace(); }
}
最好指定编码类型。(“utf-8”)。不过,这对你的任务可能并不重要。您可能还需要附加到文件中,而不是完全重新写入,在这种情况下,您应该为FileOutputStream使用不同的构造函数,
新FileOutputStream(getFileLocation(),true)
。至于许多try/catch块,请不要遵循我的示例。这就是我如何关闭我的资源,正如eclipse推荐的那样,哈哈

解析字符串 如果您有一行,如“关键字:计算机、机器人、课程”


现在您有了一个数组,您可以循环使用它,并根据需要写入/打印。

您可以使用
regex
提取单词“关键字:”后面的单词,如下所示:

String regex = ".*Keywords\\s*:(.*)\\n.*";

String extractedLine = yourText.replaceAll( regex, "$1" );

System.out.println( extractedLine );

请尝试一下!仅仅因为你发布了代码并不意味着你在解决问题上付出了任何努力。你可以通过让其他人做你的工作,在这项作业上获得A,但在期末考试中你会得到F。提示:研究
String\split()
String\startsWith()
(你发布的上述代码显然只是随机的垃圾,与作业无关。)(如果你不明白你应该练习说“你会吃薯条吗?”)好的,提示:阅读文档中的字符串。
String regex = ".*Keywords\\s*:(.*)\\n.*";

String extractedLine = yourText.replaceAll( regex, "$1" );

System.out.println( extractedLine );