I want to detect if a string starts with any of these "A(", "((A(", "(((A(", ... As you can see the number of starting parentheses could be zero or more. My problem is that startswith() in java does not get regex as input. So, how is it possible to do so?
Asked
Active
Viewed 1,177 times
-4
-
5Naturally, you should use [a method which *does* accept a regex.](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#matches(java.lang.String)) – Matt Ball Jan 01 '14 at 02:08
-
5Every string starts with zero or more parentheses. Think about it. – Bohemian Jan 01 '14 at 02:09
-
That is absolutely brilliant – takendarkk Jan 01 '14 at 02:10
2 Answers
3
s.matches("\\(*A\\(.*")
matches
requires the entire string to match, but by putting .*
at the end of the regex (which says to match any sequence of characters) you can tell it what pattern you want the string to start with. The above will match if s
starts with zero or more (
characters, an A, and another (
. If this isn't the exact pattern you're looking for, please clarify.

ajb
- 31,309
- 3
- 58
- 84
-
Only improvement I could think now is to use `if(matcherInstance.find("^\\(*A\\("))` instead of `matches` to avoid iterating over entire String. – Pshemo Jan 01 '14 at 02:25
-
Yeah, nm, It's been a long day apparently and my brain was refusing to process that correctly at first glance. – Brian Roach Jan 01 '14 at 02:28
1
This method returns true if the specified string starts with zero or more parentheses:
public static boolean startsWithZeroOrMoreParen(String s) {
return true;
}
If you consider the null string to not have zero parentheses:
public static boolean startsWithZeroOrMoreParen(String s) {
return s != null;
}
Seem trite? It's not. This is the simplest implementation that meets the brief. Every string starts with zero or more parentheses!

Bohemian
- 412,405
- 93
- 575
- 722
-
2This is not what I meant. You didn't consider the rest of the string. After the parentheses the pattern should be "A(". I didn't ask if string starts with zero or more parentheses, I said the patterns might start with zero or more parentheses. – user3150474 Jan 01 '14 at 02:21
-
The question has changed since I posted this answer. It is now substantially different. At the time I posted, this answer answered the question as posed. – Bohemian Jan 01 '14 at 04:50