what is the regex format for the usage of ')' if and only if '(' is used earlier, or ')' is must if '(' is used? I have tried ^[a-zA-Z]+(([)]?[,]?[a-zA-Z0-9 ][. -/']?[(]?[a-zA-Z0-9][)]?)?[a-zA-Z:.])$
. But I can't make it use ')' only when '(' is being used.

- 12,316
- 13
- 72
- 135

- 53
- 7
-
you need to be more specific, what do you mean "use" ')' only when '(' is being used? Do you mean entering a sentence? or cleaning an input? – Huang Chen Jul 21 '15 at 17:56
-
I want to make sure that they are used in pair. – Sri Jul 21 '15 at 19:07
-
what do you mean used? what is the context of your program, give us some information man – Huang Chen Jul 21 '15 at 19:10
-
possible duplicate of [java regexp for nested parenthesis](http://stackoverflow.com/questions/26329339/java-regexp-for-nested-parenthesis) – nhahtdh Jul 22 '15 at 03:14
1 Answers
Regex cannot take care of context. In your case you're seeking to find context. Regex is not meant for that. You need to write a function that checks this.
Citing from this link:
In the context of formal language theory, something is called “regular” when it has a grammar where all production rules have one of the following forms:
- B -> a
- B -> aC
- B -> ε
You can read those -> rules as “The left hand side can be replaced with the right hand side”. So the first rule would be “B can be replaced with a”, the second one “B can be replaced with aC” and the third one “B can be replaced with the empty string” (ε is the symbol for the empty string).
So what are B, C and a? By convention, uppercase characters denote so called “non-terminals” - symbols which can be broken down further - and lowercase characters denote “terminals” - symbols which cannot be broken down any further.
In your case you are looking for something like:
(\([x].*\)[x])*
I added the [x]
to stand for an x
number of times (it's not part of the regex convention of course). As you can see by the definition of regex, there's no way to represent such expression in a way that complies with regex definition.
This is not just a "grey" definition issue. Creating a regex-like language to solve problems like the one you noted here is much more complicated (algorithmic and complexity wise). It's a totally different problem domain to try and patternize the type of problems as the one you mentioned here.

- 21,182
- 26
- 82
- 121