WikiGalaxy

Personalize

String Matching with Wildcards

Wildcard Basics

Wildcards are special characters used to match patterns within strings. They are commonly used in search operations to find strings that follow a specific pattern.

Asterisk (*) Wildcard

The asterisk (*) wildcard matches zero or more characters in a string. It is useful for finding strings with varying lengths.


      public class WildcardExample {
          public static void main(String[] args) {
              String pattern = "a*b";
              String text = "acb";
              System.out.println(text.matches(pattern)); // Output: true
          }
      }
      

Console Output:

true

Question Mark (?) Wildcard

Single Character Matching

The question mark (?) wildcard matches exactly one character. It's useful for finding strings where a specific character can vary.


      public class WildcardExample {
          public static void main(String[] args) {
              String pattern = "a?c";
              String text = "abc";
              System.out.println(text.matches(pattern)); // Output: true
          }
      }
      

Console Output:

true

Combining Wildcards

Complex Pattern Matching

You can combine wildcards to create complex patterns for string matching. This allows for flexible search criteria.


      public class WildcardExample {
          public static void main(String[] args) {
              String pattern = "a*b?d";
              String text = "aabcd";
              System.out.println(text.matches(pattern)); // Output: true
          }
      }
      

Console Output:

true

Character Classes

Defining Character Sets

Character classes allow you to define a set of characters to match within brackets []. This is useful for specifying multiple possible characters at a position.


      public class WildcardExample {
          public static void main(String[] args) {
              String pattern = "[a-c]x";
              String text = "bx";
              System.out.println(text.matches(pattern)); // Output: true
          }
      }
      

Console Output:

true

Negating Character Classes

Excluding Characters

By using a caret (^) inside a character class, you can negate it, specifying characters that should not be matched.


      public class WildcardExample {
          public static void main(String[] args) {
              String pattern = "[^a-c]x";
              String text = "dx";
              System.out.println(text.matches(pattern)); // Output: true
          }
      }
      

Console Output:

true

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025