regex java replace all

Asked

Viewed 1,621 times

0

String url = "/users/{id}/books/{id_book}";

url = url.replaceAll("{\\w*}", "\\w*");

System.out.println("result url:" + url);

Trying to replace with regex, and returns me the following error:

Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition
{\w*}
    at java.util.regex.Pattern.error(Pattern.java:1955)
    at java.util.regex.Pattern.closure(Pattern.java:3157)
    at java.util.regex.Pattern.sequence(Pattern.java:2134)
    at java.util.regex.Pattern.expr(Pattern.java:1996)
    at java.util.regex.Pattern.compile(Pattern.java:1696)
    at java.util.regex.Pattern.<init>(Pattern.java:1351)
    at java.util.regex.Pattern.compile(Pattern.java:1028)
    at java.lang.String.replaceAll(String.java:2223)
    at br.com.rileyframework.TestRegex.main(TestRegex.java:10)

Outcome I hope:

/users/\w*/books/\w*
  • You replace {id} and {id_book} with { w*} ?

1 answer

2


You need to do the escape of the keys.

String url = "/users/{id}/books/{id_book}";
url = url.replaceAll("\\{\\w*\\}", "\\\\w*");
System.out.println("result url:" + url);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.