-6

I have a string that looks like this:

String a = "name:string, age:int, address:string,city:string, zip:int";

The string is separated by , and between : it is the fieldName and type. There might be space between each value but any space should be ignored.

What I want is to convert this string into an arrayList that only contents fieldName.

So the above example will become

List<String> result = new ArrayList<>; and in the result there should be values of name, age, address, city, zip. Everything else should be ignored.

How do i do this with regex in Java?

I can achieve this by first do the split by , then split the string array by :, and take the first element of the array then added to a list.

The reason i m asking is because I want to know if there is a more elegant way to do this with regex.

OPK
  • 4,120
  • 6
  • 36
  • 66
  • Can someone comment why the downvote? – OPK Aug 20 '19 at 20:13
  • @Andreas i added what i have tried in the description. The whole reason to ask this is to check if i can do it in one step instead of multiple – OPK Aug 20 '19 at 20:22
  • 1
    That's not how the original question read. It read as "I want this, tell me how to do it". --- You still don't **show** the *code* of what you have tried. Don't explain the code, show it! – Andreas Aug 20 '19 at 20:25

2 Answers2

0

The following regex will give you the results you want

[a-z]+[^, ](?=:)

The first parentheses is called a look ahead, so anything that is before a : will be selected, the first set of brackets says we want any character a-z (note these are case sensitive so add +[A-Z] if caps may be used), the final set of brackets says no , or space

to use this in java you would write something along the lines of

Pattern.compile("[a-z]+[^, ](?=:)")
       .matcher(a)
       .find();

I use this site a lot to test regex's it's a really helpful tool

0
String[] b = a.split(":[^,]+(?:, *)?");

Or:

String[] b = Pattern.compile("[^, ]+(?=:)").matcher(a).results()
                    .map(r -> r.group()).toArray(String[]::new);
Andreas
  • 154,647
  • 11
  • 152
  • 247