Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse this string with regex?

Tags:

java

regex

I have a string like:

"GOOG",625.00,"-1.95 - -0.31%"

I'm using this pattern, and it isn't matching. I'm trying to get GOOG. What am I doing wrong?

Pattern pattern = Pattern.compile("^\"([^\"]+)");
Matcher matcher = pattern.matcher(line);

if (matcher.matches()) {
    Log.i(TAG, matcher.group(0));
} else {
    Log.i(TAG, "no match");
}
like image 887
Joren Avatar asked Jul 09 '26 03:07

Joren


1 Answers

The problem is you're not running matcher.find() so the expression is never really evaluated. What you have will work fine if you just change it to:

if (matcher.find()) {

Though this seems like it'd be easier if you just used the String.split method (or better yet, use a library for parsing CSV files):

String temp = "\"GOOG\",625.00,\"-1.95 - -0.31%\"";
String[] parts = temp.split(",");
String symbol = temp[0].replaceAll("\"", "");
like image 170
Mark Elliot Avatar answered Jul 11 '26 09:07

Mark Elliot