简体   繁体   English

如何找到行的一部分Java?

[英]how to find part of line java?

I need some portion of the file to display.Actually by using Matcher and Pattern I found a word in the file .By using Matcher.start() and Matcher.end() I got the postion of the word.But how can i get the words before and after this word without splitting.This is like a home work program.Plz help me out. 我需要显示文件的一部分。实际上通过使用Matcher和Pattern我在文件中找到了一个单词。通过使用Matcher.start()和Matcher.end()我得到了单词的位置,但是我怎么得到这个单词之前和之后的单词都不会分裂。这就像一个家庭作业程序。请帮助我。

For example:File.txt : 例如:File.txt:

contains the above lines only.then in that I found "the" word at 23 and 26 postion.Now I want "some portion of" , "file to display." 仅包含上述几行。然后我在23和26位找到了“ the”一词。现在,我希望显示“文件的一部分”,“文件”。 words. 话。

Actually ,by using String.substring(start,end) we will get some part but I need exactly words.If i take substring it is giving, cutting part of the words. 实际上,通过使用String.substring(start,end),我们会得到一部分,但我确实需要单词。如果我采用substring的话,则会切掉一部分单词。

The trick is to remember that the String.range method is really cheap in Java. 诀窍是要记住String.range方法在Java中真的很便宜。 So what you do is get the substrings that are the “string before the matched pattern” and the “string after the matched pattern” and apply suitable other regular expressions to extract the answers you want from those. 因此,您要做的就是获取子字符串,这些子字符串是“匹配模​​式之前的字符串”和“匹配模式之后的字符串”,并应用其他合适的正则表达式从中提取所需的答案。

String toFind = "day";
String sentence = "wolfrevokcatS no snoitseuq krowemoh tsop ot yad enif a si tI";

char[] charArray = sentence.toCharArray();

String reversedSentence = "";

for(int i = 0; i < charArray.length; ++i) {
    reversedSentence += charArray[charArray.length - i - 1];
}

System.out.println(reversedSentence);
boolean matches = reversedSentence.matches(".+" + toFind + ".+");

if(matches) {

    int start = reversedSentence.indexOf(toFind);
    int end = start + toFind.length();

    System.out.println("Before word to find: " + reversedSentence.substring(0, start));
    System.out.println("Word to find: " + reversedSentence.substring(start, end));
    System.out.println("After word to find: " + reversedSentence.substring(end, reversedSentence.length()));
}

Here is a solution that uses regular expressions. 这是使用正则表达式的解决方案。 If you manage to understand this code, you'll do well with string manipulation in Java. 如果您设法理解此代码,那么Java字符串处理将做得很好。 I haven't proved it's correct for all inputs, I leave it as an exercise to the question's author. 我还没有证明所有输入都是正确的,我把它留给问题作者练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM