1

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:

  • This answer is not what I'm looking for. It allows dual * and dual #
  • ^\*([0-9]|\*?)*#$ doesn't help with dual stars
GV_FiQst
  • 1,191
  • 9
  • 27

1 Answers1

3

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
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • What is the purpose of `?:` in your regex? – GV_FiQst Mar 28 '18 at 23:29
  • @GV_FiQst That is a [non-capturing group](https://stackoverflow.com/questions/3512471/what-is-a-non-capturing-group-what-does-do). Since the value captured by the group is not used, there is no need to store anything the group matches in the memory. – Wiktor Stribiżew Mar 28 '18 at 23:48