Reputation: 169
How could I write a regex that will match a string containing only question marks
"???" > true
"????" > true
"? " > true
"?a?" > false
"?a" > false
Thanks in advance !
Edit: 2 cases I missed:
"? " > true
"?? ? ?" > true
Upvotes: 2
Views: 27530
Reputation: 596
Given that the string can contain spaces (as per the edit), the correct regex is
^[ ?]*[?][ ?]*$
This allows for any number of spaces and question marks and guarantees that at least one question mark is present.
Upvotes: 4
Reputation: 6800
/^(?=\s*\?)[?\s]+$/
An Explanation:
^
Match the beginning of the string
(?= ... )
Lookahead, a zero-width assertion about what's coming up in the string, here used to assert:
\s*
any amount of white space, followed by:
\?
A literal question mark. Ensuring there's at least one question mark in the string.
[?\s]
Match a question mark, or whitespace.
+
One or more times.
$
Match the end of the string.
Upvotes: 1
Reputation: 34367
Use regex as ^\\?+$
String regex = "^\\?+$";
Pattern pattern = Pattern.compile(regex);
System.out.println(pattern.matcher("?").find());//prints true
System.out.println(pattern.matcher("??").find());//prints true
System.out.println(pattern.matcher("????").find());//prints true
System.out.println(pattern.matcher("?a?").find());//prints false
System.out.println(pattern.matcher("?a").find());//prints false
Upvotes: 0
Reputation: 15284
Maybe it is a better idea to escape the question mark (as I always escape all symbols):
^\?+$
You don't need a square bracket either.
Upvotes: 2
Reputation: 726619
That would be as simple as this:
^[?]+$
The expression requires that the string from the start ^
to the end $
consisted of question marks [?]
(square brackets prevent interpretation as meta-character) repeated one or more times +
.
Upvotes: 8