Java Regular Expression character classes predefined

Introduction

The following table lists the predefined Java Regular expression character classes:

CharacterMatches
\d any digit
\D any non-digit
\w any word character
\W any nonword character
\s any white-space character
\S any non-whitespace character
public class Main {
  public static void main(String[] args) {
    String firstString = "This sentence ends in 5 stars *****";
     //  www  .j a  va 2 s .c  o  m
    System.out.printf("Original String 1: %s\n", firstString);

    // replace words with 'word'
    System.out.printf("Every word replaced by \"word\": %s\n\n",
       firstString.replaceAll("\\w+", "____"));

  }
}
public class Main {
  public static void main(String[] args) {
    String firstString = "in 5333 stars *****";
     //from  ww  w.  j a  v  a2 s.  com
    System.out.printf("Original String 1: %s\n", firstString);

    firstString = firstString.replaceFirst("\\d", "&&&");

    System.out.printf(firstString);
  }
}
import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    String firstString = "1, 2, 3, 4, 5, 6, 7, 8";

    System.out.printf("%s\n", firstString);

    String[] results = firstString.split(",\\s*"); // split on commas
    System.out.println(Arrays.toString(results)); // display results

  }/*from  www .j av a 2 s  .c om*/
}



PreviousNext

Related