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
HGA03630@nifty.ne.jp - 03 Oct 2005 19:50 GMT
> part[0] = "abc";
> part[1] = "abc";
> part[2] = "abc";
> part[3] = "abc";
I don't understand your requirement.
Andrew Thompson - 03 Oct 2005 20:08 GMT
>>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. ;-)
HGA03630@nifty.ne.jp - 04 Oct 2005 00:32 GMT
Then,
String s = "{abc}{def}{X}{Y}";
String[] p = s.split("\\{|\\}\\{|\\}");
for (String ss : p){
System.out.println(ss);
}
Roedy Green - 03 Oct 2005 20:17 GMT
> 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
"\\{|\\}"

Signature
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
shakah - 03 Oct 2005 21:09 GMT
> Hello:
>
[quoted text clipped - 16 lines]
> 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[i] ;
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]