Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string contains two asterisk characters?

Tags:

java

string

We have a string input and the following combinations are valid (e.g. sunday, *sunday*, sun*day*, *sun*day, su*nda*y) If it contains only a single asterisk, then it is a bad input.

So given the above input, how do I check to see if the string contains multiple asterisks.

like image 519
Achaius Avatar asked Jul 28 '10 07:07

Achaius


2 Answers

int asterisk1 = input.indexOf('*');
boolean hasTowAsterisks = asterisk1 != -1 && input.indexOf('*', asterisk1+1) != -1;

Edit: this solution assumed that the requirement was "has at least two asterisks".

like image 130
Joachim Sauer Avatar answered Sep 22 '22 10:09

Joachim Sauer


You could use String.matches with a regular expression:

"^.*(?:\\*.*){2}$"

If you want exactly two asterisks:

"^[^*]*(?:\\*[^*]*){2}$"

Though for this task it might be simpler just to iterate over the string and count the asterisks.

like image 42
Mark Byers Avatar answered Sep 22 '22 10:09

Mark Byers