1

I am struggling to implement the following,

lets say I have string :

 ( z )  ( A ( z )  ( A ( z )  ( A ( z )  ( A ( z )  ( A )  )  )  )  ) 

I want to write a regex that takes out all characters that have a braked to their left and right. i.e. I would like this to return:

 ( z ) ( z ) ( z ) ( z ) ( z ) ( A ) 

I have tried a combination of regex's like: (\\s\\S( \\W \\)\\s\\S)

thanks daniel

dgamma3
  • 2,333
  • 4
  • 26
  • 47
  • Just escape the parens. They have special meaning in regex. – Marko Topolnik Oct 14 '12 at 11:50
  • 3
    Regex is not suitable for parsing nested structures like this. Writing your own parser for this will give you a better solution. http://stackoverflow.com/a/133684/1583 – Oded Oct 14 '12 at 11:50

1 Answers1

0

This expression should work:

Pattern.compile("\\(\\s*\\w+\\s*\\)").matcher(input);

Literal parens need to be escaped in the regex and I think you've got a few extra ingredients there. The regex I show allows whitespace before and after the word chars contained within parens.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • ok, not working with this code though: Matcher regexMatcher = checkRegex.matcher( "\\(\\s*\\w+\\s*\\)" ); while ( regexMatcher.find() ){ if (regexMatcher.group().length() != 0){ System.out.println( regexMatcher.group() ); }} – dgamma3 Oct 14 '12 at 11:53
  • Why didn't you paste the exact expression the way I wrote it? You use a single backslash in front of the paren. That's wrong. – Marko Topolnik Oct 14 '12 at 11:56
  • well, my code doesnt even work if I Do: Pattern checkRegex = Pattern.compile("s"); Matcher regexMatcher = checkRegex.matcher("\\w"); – dgamma3 Oct 14 '12 at 11:56
  • 1
    Yes, now I notice it. One passes the **input string** to the matcher and the regex to `Pattern.compile`. You have it the wrong way. – Marko Topolnik Oct 14 '12 at 11:58