2

I have a String like this:

"0008934","1801 W NORMATOWN ROAD","ROMEOVILLE","IL","US","60446","8158866981","Y"

I would like to extract all the values inside double quotes. Could you please help me to accomplish the task.

This is what I am expecting:

0008934
1801 W NORMATOWN ROAD
ROMEOVILLE
IL
US
60446
8158866981
Y

Anyone can you pleas help me?

3
  • Use () to group anything inside "" and then use Matcher#find() and Matcher#group() Commented Apr 5, 2013 at 13:16
  • 4
    Is the input CSV? If so you need to handle escaped quotes, or better yet use a proper CSV parser. Commented Apr 5, 2013 at 13:17
  • I am using java code only... Commented Apr 5, 2013 at 13:22

4 Answers 4

7

You can do like this:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexTest {

    public static void main(String[] args) {
        String strInput = "\"0008934\",\"1801 W NORMATOWN ROAD\",\"ROMEOVILLE\",\"IL\",\"US\",\"60446\",\"8158866981\",\"Y\"";
        Pattern pattern = Pattern.compile("\"([^\"]*)\"");
        Matcher matcher = pattern.matcher(strInput);
        while (matcher.find()) {
            System.out.println(matcher.group(1));
        }
    }
}

Output:

0008934
1801 W NORMATOWN ROAD
ROMEOVILLE
IL
US
60446
8158866981
Y
Sign up to request clarification or add additional context in comments.

1 Comment

1 minute and 9 sec to the response, really fast ;) +1
2

You may also want to consider OpenCSV, a light-weight and simple open-source library consisting of only a few Java classes. Since your input is CSV, OpenCSV can do this for you.

Comments

1

Use strip the leading and trailing quotes, then split on ","

String[] parts = input.replaceAll("(^\")|(\"$)", "").split("\",\"");

2 Comments

This approach forbids the use of escaped quotes in the values.
@Thomas That's true, but his example did not have one, and I thought if it was important he would surely have included one
0

Once you have a problem and try to solve it with a regex, you have two problems.
Consider this:

String[] list = input.split(",");  
foreach (String str : list){  
    str.replaceAll("\"","");
}

4 Comments

, (comma) cannot be used within the values with this approach
@JavaMentor, from the example you can't tell it should be.
yes, you are right, but this is quite common with addresses right? And the sample was an address
@JavaMentor, yep, but that's up to OP to decide.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.