how to find part of line java?
I need some portion of开发者_如何学Go 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.
For example: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." 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 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. I haven't proved it's correct for all inputs, I leave it as an exercise to the question's author.
The trick is to remember that the String.range
method is really cheap in 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.
精彩评论