Java regular expressions
Hi folks, I'm trying to read a line of text from a file and set a parameter based on the string. The code below has a string called match which is an example of how the line of text may appear.
Now what i'm wanting to match is any alphanumeric string that occurs after the '='. So I think i've got the second part correct, but i'm not sure about the rest?
String regex ="[0-9a-zA-Z]";//Regular expression
String output_mode_param;
String match ="output_mode=xxx"//where xxx is any alphanumeric string
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(match);
if(matcher.find()){
output_mode_param = matcher.group();
System.out.println(output_mode_param);
}
else{
System.out.println("Not Found");
}
[1127 byte] By [
PaulStata] at [2007-11-27 5:45:52]

Three suggestions:
1 - you can split the line on the "=" sign. Have a look at String's split(...) method which returns a String[].
2 - Perhaps you're reinventing something a Properties file can do for you:
http://java.sun.com/docs/books/tutorial/essential/environment/properties.html
3 - Try something like this:String regex = "[^\\=]+"; //Regular expression
String match = "output_mode=xxx"; //where xxx is any alphanumeric string
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(match);
while(matcher.find()) {
System.out.println(matcher.group());
}
Good luck.
String regex = "[^\\=]+";
That will match the text before the equals sign as well as after it. I would change it to String regex = "[^=]+$";
or maybe String regex = "(?<==).+";
But either of those regexes could still return incorrect results, depending on the format of the text file. Can it contain comments, like a properties file, or group headers like an INI file? You would have to filter out any special cases like those before applying the regex.