1

I'm trying to split a String using regex with Java. The string looks like this: {'tata','toto','titi'} But {} describes the order of the preceding liberal, so it doesn't work for me.

What regex should I use to get this result :

tata
toto
titi
3
  • 2
    Can you post what code you have so far? Commented Nov 18, 2014 at 18:30
  • \d{X} means in regex that it occurs X times. how to ignore the braces Commented Nov 18, 2014 at 18:32
  • 3
    Are you trying to parse an existing data-interchange format? If so there may be a better solution than regex. Commented Nov 18, 2014 at 18:34

3 Answers 3

2

You can use this regex:

String str = "{'tata','toto','titi'}";
String[] arr = str.split("[{},']+");
//=> tata, toto, titi

There is no need to escape { or } inside character class.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use \ to disable the special meaning of any character in a regex.

Since \ itself has a special meaning in a String you will need to duplicate it if you specify your regex directly in a String literal in java. So replace "{something}" with \\{something\\}".

Comments

1
String a = "{'tata','toto','titi'}"
a = a.replace("{'", ""); // get rid of opening bracket and singlequote
a = a.replace("'}", ""); // get rid of ending bracket and singlequote
String[] b = a.split("','"); // split on commas surrounded by singlequotes

This should give you an array of just the words you want. I guess it's not specifically regex, but it should do the right thing anyway.

1 Comment

Totally forgot about replace not changing the original string. Thanks for setting me straight, whoever you were.

Your Answer

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