GV_FiQst
GV_FiQst

Reputation: 1567

Java USSD code regex pattern

How can I test a string is a valid ussd code? I was trying to write my own regex but failed.

It should start with * symbol followed by any integers or another one *. Star symbol can not repeat. It mustn't have **. And the last symbol must be #. Also this symbol is allowed once.

My tests:

public static final Pattern USSD = Pattern.compile("Pattern here");

System.out.println(USSD.matcher("*123#").matches());     // Must be true
System.out.println(USSD.matcher("*1*2*3#").matches());   // Must be true
System.out.println(USSD.matcher("*1#23#").matches());    // Must be false
System.out.println(USSD.matcher("***123###").matches()); // Must be false
System.out.println(USSD.matcher("*12**3#").matches());   // Must be false

What I've already tried:

Upvotes: 1

Views: 504

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626806

You may use the following regex with matches():

(?:\*\d+)+#

See the regex demo.

In Java, declare it as

String pattern = "(?:\\*\\d+)+#";

Pattern details

  • ^ - (implicit in matches()) - start of a string
  • (?:\*\d+)+ - 1 or more occurrences of the sequence of patterns:
    • \* - a * char
    • \d+ - 1+ digits
  • $ - (implicit in matches()) - end of string.

Java demo:

List<String> strs = Arrays.asList("*123#","*1*2*3#","*1#23#","***123###","*12**3#");
Pattern pat = Pattern.compile("(?:\\*\\d+)+#");
for (String str : strs) {
    System.out.println(str + ": " + pat.matcher(str).matches());
}

Output:

*123#: true
*1*2*3#: true
*1#23#: false
***123###: false
*12**3#: false

Upvotes: 4

Related Questions