-
search text
I have a file and would want to search for all the words starting with say "ABC" and display them.
For eg:
askjaas
123_ABC1
alkdjsad
238_ABC222
akjsdlksada
asdkjlhfdsa
233_ABC34323
kjsdfhlsd
.........
I tried using ABC* but it didn't work out. Also, I want only the words ABC1,ABC222,ABC34323 to be printed out. could someone please help me solve it? I have the same code where I could search for a normal word and points out its index number.
Code:
public class NewClass {
public static void main(String[] args){
//Search String
String searchText = "ABC";
//File to search (in same directory as .class file)
String fileName = "C:\\chinese1.txt";
//StringBuilder allows to create a string by concatinating
//multiple strings efficiently.
StringBuilder sb =
new StringBuilder();
try {
//Create the buffered input stream, which reads
//from a file input stream
BufferedInputStream bIn =
new BufferedInputStream(
new FileInputStream(fileName));
//Holds the position of the last byte we have read
int pos = 0;
//Holds #of available bytes in our stream
//(which is the file)
int avl = bIn.available();
//Read as long as we have something
while ( avl != 0 ) {
//Holds the bytes which we read
byte[] buffer = new byte[avl];
//Read from the file to the buffer
// starting from <pos>, <avl> bytes.
bIn.read(buffer, pos, avl);
//Update the last read byte position
pos += avl;
//Create a new string from byte[] we read
String strTemp =
new String(buffer);
//Append the string to the string builder
sb.append(strTemp);
//Get the next available set of bytes
avl = bIn.available();
}
}
catch(IOException ex) {
ex.printStackTrace();
}
//Get the concatinated string from string builder
String fileText = sb.toString();
//Displays the index location in the file for a given text.
// -1 if not found
System.out.println(
"Position in file : " +
fileText.indexOf(searchText));
}
}
-
:(think): :(think)::(think):
-
Hi. You can use Reg Exp for this aim. you can find more information on official website Oracle.
-
You could also use String Tokenizer and look at the first 3 characters of each token. I don't know how this method compares to using regex.
-
StringTokenizer does work with regexp and it is used for to break a string into tokens. )) It is strange solve for search appropriate text.