In this article, we will shed light on how to make a character or a group optional in regex.

First, we will explain what the quantifier (?) means. Then, we will showcase how to implement optionality using regular expressions.

Question Mark Quantifier ? in Regex

Typically, an optional character is specified using the “?” quantifier.

The question mark means that the preceding character or group is optional and may appear zero or one time.

In short, we can denote optionality by suffixing characters with “?”.

For instance, the regex “https?://” matches both “http://” and “https://“. Here, the “s” character is optional in the matching string.

Matching Optional Character Example

Now, let’s exemplify the use of the question mark quantifier in regular expressions.

First, we will use it to match any character that may or may not be present in a given string:

    
        public static void main(String[] args) {
            Pattern.compile("tag:.?>$")
                    .matcher("tag:A>")
                    .find(); // true
            Pattern.compile("tag:.?>$")
                    .matcher("tag:BB>")
                    .find(); // false
        }
    

As shown above, the regex “tag:.?” checks if the given string contains the word “tag:“, followed by any single character optionally.

The pattern ”>$” indicates that the matching string should end with “>”.

Next, let’s add an example to match a specific optional character:

    
        public static void main(String[] args) {
            Pattern.compile("https?://")
                    .matcher("http://devwithus.com")
                    .find(); // true
            Pattern.compile("https?://)
                    .matcher("https://devwithus.com")
                    .find(); // true
            Pattern.compile("https?://)
                    .matcher("httpc://devwithus.com")
                    .find(); // false
        }
    

As we can see, the regex “https?://” matches the word “http” with or without the letter “s”.

Please note that the question mark is a special character. So, to make it optional, we need to escape it using a slash “\?”.

Optional Group of Characters

Typically, we can use parentheses to wrap a group of characters to make them not mandatory.

Here is a Java example of using an optional group of characters:

    
        public static void main(String[] args) {
            Pattern.compile("^devwith(us)?.com$")
                    .matcher("devwithus.com")
                    .find(); // true
            Pattern.compile("^devwith(us)?.com$")
                    .matcher("devwith.com")
                    .find(); // true
            Pattern.compile("^devwith(us)?.com$")
                    .matcher("devwithjava.com")
                    .find(); // false
        }
    

The regular expression matches both “devwith.com” and “devwithus.com” because the group of characters “us” is optional. Hence, it may be present or absent.

Please notice that the anchor ”^” matches the start of the input string.

We can use the pipe symbol “|”, which denotes the OR operator, to match multiple optional groups:

    
        public static void main(String[] args) {
            String regex = "Spring (boot|security|data)?";
            Pattern.compile(regex)
                    .matcher("Spring boot")
                    .find(); // true
            Pattern.compile(regex)
                    .matcher("Spring data")
                    .find(); // true
        }
    

As we can see, the regex matches patterns that may or may not include the group of words (“boot”, “security”, and “data”).

  • The parentheses wrap the group elements

  • The pipe separates each element

  • The question mark denotes optionality

Conclusion

To sum it up, we covered in-depth how to use optional characters in regular expressions.

Along the way, we demonstrated how to make a single character or a group of words not mandatory in a given string.