1
String TextValue = "hello{MyVar} Discover {MyVar2} {MyVar3}";
String[] splitString = TextValue.split("\\{*\\}");

What I'm getting output is [{MyVar, {MyVar2, {MyVar3] in splitString

But my requirement is to preserve those delimiters {} i.e. [{MyVar}, {MyVar2}, {MyVar3}].

Required a way to match above output.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Nagaraj
  • 78
  • 9

2 Answers2

2

Use something like so:

Pattern p = Pattern.compile("(\\{\\w+\\})");
String str = ...
Matcher m = p.matcher(str);
while(m.find())
    System.out.println(m.group(1));

Note, the code above is untested but that will look for words within curly brackets and place them in a group. It will then go over the string and output any string which matches the expression above.

An example of the regular expression is available here.

npinti
  • 51,780
  • 5
  • 72
  • 96
0

Thanks kelvin & npinti.

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

public class CreateMatcherExample {
    public static void main(String[] args) {
        String TextValue = "hello{MyVar} Discover {My_Var2} {My_Var3}";
        String patternString = "\\{\\w+\\}";

        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(TextValue);

        while(matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}
N00b Pr0grammer
  • 4,503
  • 5
  • 32
  • 46
Nagaraj
  • 78
  • 9
  • 3
    2 Minor notes: On SO if an answer solves your problem, you mark that answer as correct, posting your solution is usually recommended only if you end up with something different from the provided answers. Secondly, the code you are using is printing the match by the expression. Although this works, it will break should you add more stuff to the expression which you do not want to have in the end result. – npinti Sep 02 '16 at 06:33