Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to remove round brackets from a string

Tags:

java

regex

i have a string

String s="[[Identity (philosophy)|unique identity]]";

i need to parse it to .

s1 = Identity_philosphy 
s2= unique identity

I have tried following code

Pattern p = Pattern.compile("(\\[\\[)(\\w*?\\s\\(\\w*?\\))(\\s*[|])\\w*(\\]\\])");
  Matcher m = p.matcher(s);
while(m.find())
{
....
}

But the pattern is not matching..

Please Help

Thanks

like image 670
user2818196 Avatar asked Oct 03 '13 09:10

user2818196


People also ask

How do you remove brackets from text in Python?

In python, we can remove brackets with the help of regular expressions. # pattern is the special RE expression for finding the brackets.

What is parenthesis in regex?

Parentheses Create Numbered Capturing Groups Besides grouping part of a regular expression together, parentheses also create a numbered capturing group. It stores the part of the string matched by the part of the regular expression inside the parentheses. The regex Set(Value)? matches Set or SetValue.


1 Answers

Use

String s="[[Identity (philosophy)|unique identity]]";
String[] results = s.replaceAll("^\\Q[[\\E|]]$", "")    // Delete double brackets at start/end
      .replaceAll("\\s+\\(([^()]*)\\)","_$1")           // Replace spaces and parens with _
       .split("\\Q|\\E");                               // Split with pipe
System.out.println(results[0]);
System.out.println(results[1]);

Output:

Identity_philosophy
unique identity
like image 136
Ryszard Czech Avatar answered Oct 21 '22 14:10

Ryszard Czech