I would like to match a string within parentheses like:
(i, j, k(1))
^^^^^^^^^^^^
The string can contain closed parentheses too. How to match it with regular expression in Java without writing a parser, since this is a small part of my project. Thanks!
Edit:
I want to search out a string block and find something like u(i, j, k)
, u(i, j, k(1))
or just u(<anything within this paired parens>)
, and replace them to __u%array(i, j, k)
and __u%array(i, j, k(1))
for my Fortran translating application.
Introduction. A cool feature of the . NET RegEx -engine is the ability to match nested constructions, for example nested parenthesis.
You can use the Pattern. matches() method to quickly check if a text (String) matches a given regular expression. Or you can compile a Pattern instance using Pattern. compile() which can be used multiple times to match the regular expression against multiple texts.
The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.
As I said, contrary to popular belief (don't believe everything people say) matching nested brackets is possible with regex.
The downside of using it is that you can only up to a fixed level of nesting. And for every additional level you wish to support, your regex will be bigger and bigger.
But don't take my word for it. Let me show you. The regex:
\([^()]*\)
Matches one level. For up to two levels, you'd need:
\(([^()]*|\([^()]*\))*\)
And so on. To keep adding levels, all you have to do is change the middle (second) [^()]*
part to ([^()]*|\([^()]*\))*
(check three levels here). As I said, it will get bigger and bigger.
For your case, two levels may be enough. So the Java code for it would be:
String fortranCode = "code code u(i, j, k) code code code code u(i, j, k(1)) code code code u(i, j, k(m(2))) should match this last 'u', but it doesnt.";
String regex = "(\\w+)(\\(([^()]*|\\([^()]*\\))*\\))"; // (\w+)(\(([^()]*|\([^()]*\))*\))
System.out.println(fortranCode.replaceAll(regex, "__$1%array$2"));
Input:
code code u(i, j, k) code code code code u(i, j, k(1)) code code code u(i, j, k(m(2))) should match this last 'u', but it doesnt.
Output:
code code __u%array(i, j, k) code code code code __u%array(i, j, k(1)) code code code u(i, j, __k%array(m(2))) should match this last 'u', but it doesnt.
In the general case, parsers will do a better job - that's why people get so pissy about it. But for simple applications, regexes can pretty much be enough.
Note: Some flavors of regex support the nesting operator R
(Java doesn't, PCRE engines like PHP and Perl do), which allows you to nest arbitrary number of levels. With them, you could do: \(([^()]|(?R))*\)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With