liveBook · Manning

Character class

As explained in The Well-Grounded Rubyist, Fourth Edition

The word character class is the regular-expression character class matching letters, numbers, and underscore.

A character class matches one character from a constrained set. The word character class, written \w, matches letters, numbers, and underscore, making it useful for recognizing word-like clumps without accepting every possible character. section 11.3.3 section 11.7.1

Scanning word characters

Ruby can scan each word-like run with /\w+/: "one two three".scan(/\w+/) produces "one", "two", and "three". The + quantifier expands the one-character class into one-or-more consecutive matches. section 11.7.1 section 11.8

Use character-class syntax when the allowed characters need to be controlled:

  • Write an explicit class such as [dr] to match either d or r, but only one character. section 11.3.3
  • Use ranges such as [A-Fa-f0-9] for hexadecimal digits, or negate the class with a leading caret to match anything else. section 11.3.3
  • Prefer \d for digits and \w for word characters when their predefined sets express the intended constraint. section 11.3.3
>> "testing 1 2 3 testing 4 5 6".scan(/\d/)
=> ["1", "2", "3", "4", "5", "6"]

A runnable scan example shows \d matching individual digits and demonstrates the same single-character behavior used by \w. section 11.7.1

>> str = "This is an epsilon: \u03a3"
=> "This is an epsilon: Σ"
>> str.match(/\p{Greek}/)
=> #<MatchData "Σ">

A Unicode example shows how property-based classes can match a Greek character when a narrower shorthand does not express the desired character set. section 11.3.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains explicit, ranged, negated, predefined, and POSIX classes, including single-character matching and Unicode behavior.
Examples
Uses rejected, hexadecimal strings, digit scans, proper names, Unicode letters, and Greek characters as matching examples.
What it assumes
Assumes basic Ruby strings and regular-expression syntax while teaching character alternatives, ranges, negation, and predefined classes.
What you can do after
Apply it via Ruby regular expressions to recognize constrained characters, scan word-like runs, and choose Unicode-aware alternatives.
How it connects
Connects character classes to regular expressions, quantifiers, String#scan, POSIX bracket notation, and Unicode properties.

Also explained in

Compare how 9 books explain character class →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.