ratamaster
ratamaster

Reputation: 169

Regex that matches a string only with question marks

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

Answers (5)

44maagnum
44maagnum

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

FrankieTheKneeMan
FrankieTheKneeMan

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

Yogendra Singh
Yogendra Singh

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

SwiftMango
SwiftMango

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

Sergey Kalinichenko
Sergey Kalinichenko

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

Related Questions