Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regular expression and escaping meta characters

Tags:

java

regex

I am trying to write regexp for matching token embedded between two curly braces. For example if buffer Hello {World}, I want to get "World" token out of String. When I use regexp like \{*\} eclipse shows a error messages as

Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\)

Can anyone please help me? I am new to using regular expressions.

like image 698
Rajanikanth Avatar asked Oct 20 '25 20:10

Rajanikanth


1 Answers

Use this code to match string between { and }

String str = "if buffer Hello {World}";
Pattern pt = Pattern.compile("\\{[^}]*\\}");
Matcher m = pt.matcher(str);
if (m.find()) {
    System.out.println(m.group());
}

RegEx Details:

  • \\{: Match opening {
  • [^}]*: Match 0 or more of any characters that are not }
  • \\}: Match closing }
like image 155
anubhava Avatar answered Oct 23 '25 09:10

anubhava