Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pattern matching for String having "{"

Tags:

java

regex

First I did this -

String str = "{\"hits\":[{\"links_count\":6,\"forum_count\":11}],\"totalHitCount\":1}";

        Assert.assertTrue(str.matches("{\"hits\":[{\"links_count\":[0-9]{1,},\"forum_count   \":11}],\"totalHitCount\":[0-9]{1,}}"),
            "Partnership message does not appear");

This got me following error -

 Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition
{"hits":[\{"links_count":[0-9]{1,},"forum_count":11}],"totalHitCount":[0-9]{1,}}

Then I did (escapes the "{") -

String str = "\\{\"hits\":[\\{\"links_count\":6,\"forum_count\":11\\}],\"totalHitCount\":1\\}";

    Assert.assertTrue(str.matches("\\{\"hits\":[\\{\"links_count\":[0-9]{1,},\"forum_count\":11\\}],\"totalHitCount\":[0-9]{1,}\\}"),
            "Partnership message does not appear");

and got the the following error -

Exception in thread "main" java.lang.AssertionError: Partnership message does not appear expected:<true> but was:<false>

What am I missing here?

like image 817
Tarun Avatar asked Jun 09 '11 04:06

Tarun


People also ask

How do you match a string with a pattern?

To match a character in the string expression against a list of characters. Put brackets ( [ ] ) in the pattern string, and inside the brackets put the list of characters. Do not separate the characters with commas or any other separator. Any single character in the list makes a successful match.

What is matching string pattern?

A string enclosed within double quotes ('"') is used exclusively for pattern matching (patterns are a simplified form of regular expressions - used in most UNIX commands for string matching).

What is pattern matching give an example?

For example, x* matches any number of x characters, [0-9]* matches any number of digits, and . * matches any number of anything. A regular expression pattern match succeeds if the pattern matches anywhere in the value being tested.

What does \\ mean in regex?

The backslash character (\) in a regular expression indicates that the character that follows it either is a special character (as shown in the following table), or should be interpreted literally. For more information, see Character Escapes. Escaped character. Description. Pattern.


1 Answers

You don't need to escape { [ in your input. But you need to escape [ ] in your regex.

Try this:

String str = "{\"hits\":[{\"links_count\":6,\"forum_count\":11}],\"totalHitCount\":1}";

System.out.println(str.matches("\\{\"hits\":\\[\\{\"links_count\":[0-9]{1,},\"forum_count\":11\\}\\],\"totalHitCount\":[0-9]{1,}\\}"));
like image 132
Prince John Wesley Avatar answered Oct 13 '22 01:10

Prince John Wesley