Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Parse File

Status
Not open for further replies.

dcusick

Technical User
Aug 9, 2000
271
US
What's up all? I have a quick question for anyone out there... I have a file that i have to run through and parse... I want to extract all values of the format r00, where 00 are any numbers. The problem is that I could have r1, or r11. So I never know if there are two digits in the string, or just one. I have the code written that extracts the contents of the file and places them in a string buffer. I can run through each line, character by character, but I just don't know where to go after that.. I think it's pretty safe to say that if an 'r' is encountered and a number follows it, then I want it... Any suggestions?
 
This is a bit cra*, and there are probably much better algorithms out there, but ...

Code:
BufferdReader br = new BufferedReader(new FileReader(file));
String line = "";
while ((line = br.readLine()) != null) {
  // miss out the 'r' but get the rest
  int i = Integer.parseInt(line.substring(1, line.length());
}
 
Thanks for the reply, but that didn't seem to work for me... I kept getting NumberFormatExceptions being thrown everywhere... I figured out a way to do it.. It's probably exhaustive, but it definitely works, so that's the most important part... Basically, if I find an 'r', I just grab the next two characters. If they're both digits, I append them to the r, else I only append one of them.

Code:
	for(int i=0; i<strLine.length(); i++) {
	    if (strLine.substring(i,i+1).equals("r")) {
		nextChar = strLine.charAt(i+1);

		if ((i+2) >= strLine.length()) {
		    nexxtChar = 'z';
		} else {
		    nexxtChar = strLine.charAt(i+2);
		}
		if (Character.isDigit(nextChar)) {
		    if (Character.isDigit(nexxtChar)) {
			regNumb = strLine.substring(i+1,i+3);
		    } else {
			regNumb = strLine.substring(i+1,i+2);
		    }
		    regVals.add((String) strLine.substring(i,i+1) + regNumb);
		}	
	    }
	}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top