Skip to main content
Log in

Mojo struct

CharacterClass

struct CharacterClass

Represents a character class in a regular expression.

Character classes represent sets of characters that can match at a position, such as digits, letters, or custom sets defined with brackets.

In regex syntax, character classes can be predefined (like \d for digits) or custom-defined using brackets (like [a-z] for lowercase letters). This struct provides a way to represent and work with these classes.

The struct stores both a name for the class (e.g., "digit" for \d) and the actual set of characters that belong to the class. It also provides methods to check if a given character is a member of the class.

Example usage:

var digit_class = CharacterClass("digit", "0123456789")
if digit_class.matches("5"):
print("5 is a digit")
var digit_class = CharacterClass("digit", "0123456789")
if digit_class.matches("5"):
print("5 is a digit")

Fields

  • name (String): The name of the character class.
  • chars (String): The characters that are part of this class.

Implemented traits

AnyType, Copyable, ExplicitlyCopyable, Movable, UnknownDestructibility

Methods

__init__

__init__(out self, name: String, chars: String)

Initialize a character class.

Args:

  • name (String): The name of the character class (e.g., "digit", "word").
  • chars (String): The characters that are part of this class.

matches

matches(self, c: String) -> Bool

Check if a character is in this character class.

This method determines whether a given character is a member of this character class. It does this by checking if the character is present in the chars string for this class.

Note that this method expects a single character as input. If a string with multiple characters is provided, it will return False since character classes match exactly one character at a time.

The method uses the 'in' operator to check for membership, which for strings checks if one string is a substring of another. Since we're dealing with single characters, this effectively checks if the character is one of the allowed characters in the class.

Args:

  • c (String): The character to check for membership in this class. Should be a single character.

Returns:

True if the character is in this character class, False otherwise.

Raises:

If the string operation fails (unlikely with normal usage).