String.split regular expression - need help

R

Richard

Hello:

Given a
String s = "{abc}{def}{X}{Y}";

I would like to split it into
part[0] = "abc";
part[1] = "abc";
part[2] = "abc";
part[3] = "abc";

Attempted
String[] part = s.split("^\\{|\\}\\{|\\}$");
but that gives an array with "" as a first element

Is there a better regex to extract each item inside {} in my original
string?

Thanks,
Richard
 
A

Andrew Thompson

part[0] = "abc";
part[1] = "abc";
part[2] = "abc";
part[3] = "abc";

I don't understand your requirement.

I think that should have read..

part[0] = "abc";
part[1] = "def";
part[2] = "X";
part[3] = "Y";

Perhaps the OP took 'always copy/paste' a little too
literally. ;-)
 
R

Roedy Green

String[] part = s.split("^\\{|\\}\\{|\\}$");
but that gives an array with "" as a first element

That is exactly what is should do because there is a delimiter on the
front. If your delimiter were / and you wrote

"/abc/def/"

you would expect "" abc def ""

if you wrote

"abc/def"

you would expect abc def

I think your expectations are being warped by the curliness of your
delimiters.

So the way to handle it is when you are done strip the lead and trail
"", or strip all "".

Then you can dispense with the special case ^ and $.
You could even shorten your regex to

"\\{|\\}"
 
S

shakah

Richard said:
Hello:

Given a
String s = "{abc}{def}{X}{Y}";

I would like to split it into
part[0] = "abc";
part[1] = "abc";
part[2] = "abc";
part[3] = "abc";

Attempted
String[] part = s.split("^\\{|\\}\\{|\\}$");
but that gives an array with "" as a first element

Is there a better regex to extract each item inside {} in my original
string?

Thanks,
Richard

Not a one-liner, but you could use groups, e.g.:

jc@soyuz:~/tmp$ cat grptest.java
public class grptest {
public static void main(String [] asArgs) {
java.util.regex.Pattern p =
java.util.regex.Pattern.compile(asArgs[0]) ;
System.out.println(" regex: [" + asArgs[0] + "]") ;
for(int i=1; i<asArgs.length; ++i) {
String sExpr = asArgs ;
System.out.println("input str: [" + sExpr + "]") ;
java.util.regex.Matcher m = p.matcher(sExpr) ;
while(m.find()) {
System.out.println(" match: [" + m.group(1) + "]") ;
}
}
}
}

jc@soyuz:~/tmp$ java grptest '\{([^}]*)\}' "{abc}{def}{X}{Y}"
regex: [\{([^}]*)\}]
input str: [{abc}{def}{X}{Y}]
match: [abc]
match: [def]
match: [X]
match: [Y]
 
H

HGA03630

Then,

String s = "{abc}{def}{X}{Y}";
String[] p = s.split("\\{|\\}\\{|\\}");
for (String ss : p){
System.out.println(ss);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top