Abdullah Shoaib
Abdullah Shoaib

Reputation: 2095

What is wrong with this regex to be used in JAVA?

What is wrong int the following regex to be used in a JAVA code:

    "(\\s[(]((\\w)*(\\s)*)*[)])"

This is to replace patterns in a string such as " (foo bar foo bar)". Thank you.

Upvotes: 0

Views: 211

Answers (1)

amaidment
amaidment

Reputation: 7268

First, the best way to test regex is with a Regex Tester

Second, it's helpful to get a copy of a Regex Cheat Sheet

As regards your problem, because parentheses are a reserved character in Regex, you need to escape these characters using \, but in Java, because \ is a special character, you have to escape it twice - e.g.

\\(.*\\)

This will match anything between two parentheses.

To limit it to just match word characters and spaces you could use:

\\((?:[\\w]|[\\s])*\\)

To explain what's going on here:

  • (.)* instructs to match any number of characters that match the regex in the parantheses
  • (?:.)* since parantheses means we're grouping, we add ?: to say we're not interested in the content of the group
  • [\\w]|[\\s] instructs to match either word characters or white space characters

Upvotes: 1

Related Questions