2

Cards (22)

  • Regular expression (regex)

    A character or a sequence of characters that represent a string or multiple strings
  • Regular expressions are part of the java.util.regex package
  • Regular expressions

    • Allow for quicker, easier searching, parsing, and replacing of characters in a string
    • Are used to ensure that strings contain specific contents
    • Are often used to check correct email format (@ sign is included) on form validation
  • String.matches(String regex)
    Returns true if a string matches the given regular expression
  • Regex to check if animal is "cat" or "dog"

    • animal.matches("cat|dog")
  • Regex to check if animal is "cat", "Cat", "dog", or "Dog"
    • animal.matches("[Cc]at|[Dd]og")
  • Regex to check if word rhymes with "cat"

    • word.matches("[a-z]at")
  • Regex to check if word starts with any letter and ends in "at" (uppercase or lowercase)

    • word.matches("[a-zA-Z](at|AT)")
  • Regex to check if first character is a space, number, or letter (case-sensitive)

    • word.matches("[ 0-9a-zA-Z]bcde")
  • Dot (.)

    Wildcard operator that represents any single character in regular expressions
  • Regex to check if element consists of a number followed by any other single character
    • element.matches("[0-9].")
  • Repetition operators
    Symbols that indicate the number of times a specified character appears in a matching string
  • Repetition operators
    • * (0 or more occurrences)
    • ? (0 or 1 occurrence)
    • + (1 or more occurrences)
    • {x} (x occurrences)
    • {x,y} (between x & y occurrences)
    • {x,} (x or more occurrences)
  • Regex to check if str consists of any number of any characters

    • str.matches(".*")
  • Regex to check if str consists of any character, followed by 0 or 1 character, followed by 10 characters between 0-5

    • str.matches(".?[0-5]{10}")
  • Pattern class

    Stores the format of a regular expression
  • Matcher class
    Stores a possible match between a pattern and a string
  • Initializing a Pattern and Matcher
    • Pattern p = Pattern.compile("[A-F]{5,}.*");
    Matcher match = p.matcher(str);
  • Pattern.compile()
    • Compiles the given regular expression into a pattern, which can speed up the program when the pattern is used frequently
  • Matcher.matches()
    • Checks if the regular expression given in the Pattern declaration matches a given string
  • RegEx Operations

    find() (scans the input sequence looking for the next subsequence that matches the pattern)
    split() (splits the string around matches of the given regular expression)
    replaceAll() (replaces all the occurrences of the defined regular expression found in the string with another string)
  • Regular expressions allow for very powerful validation of strings without having to write much code