liveBook · Manning

Pattern matching

As explained in Natural Language Processing in Action, Second Edition

A pattern-matching algorithm selects behavior or responses by comparing an input with predefined textual patterns.

A chatbot can recognize a greeting by checking whether an input fits a predefined pattern. Pattern matching applies hand-designed rules to text and uses the result to select a response or extract information. Patterns can describe character sequences, word sequences, parts of speech, or higher-level structures. section 1.5.2 section 12.3.1

Regular expressions provide a compact way to specify character patterns. A pattern can include alternatives, optional characters, and groups that capture parts of a match. In a chatbot, those captured parts can help determine which response to use. section 1.5.2 section 11.2.2

>>> import re             #1
>>> r = "(hi|hello|hey)[ ,:.!]*([a-z]*)"      #2
>>> re.match(r, 'Hello Rosa', flags=re.IGNORECASE)     #3
<re.Match object; span=(0, 10), match='Hello Rosa'>
>>> re.match(r, "hi ho, hi ho, it's off to work ...", flags=re.IGNORECASE)
<re.Match object; span=(0, 5), match='hi ho'>
>>> re.match(r, "hey, what's up", flags=re.IGNORECASE)
<re.Match object; span=(0, 9), match='hey, what'>

This Python example matches greetings without regard to case. It also matches “hi ho” and “hey, what”: a word following a greeting is not necessarily a person's name. section 1.5.2

>>> r = r"[^a-z]*([y]o|[h']?ello|ok|hey|(good[ ])(morn[gin']{0,3}|"
>>> r += r"afternoon|even[gin']{0,3}))[\s,;:]{1,3}([a-z]{1,20})"
>>> re_greeting = re.compile(r, flags=re.IGNORECASE)    #1
>>> re_greeting.match('Hello Rosa')
<re.Match object; span=(0, 10), match='Hello Rosa'>
>>> re_greeting.match('Hello Rosa').groups()
('Hello', None, None, 'Rosa')
>>> re_greeting.match("Good morning Rosa")
<re.Match object; span=(0, 17), match="Good morning Rosa">
>>> re_greeting.match("Good Manning Rosa")                  #2
>>> re_greeting.match('Good evening Rosa Parks').groups()    #3
('Good evening', 'Good ', 'evening', 'Rosa')
>>> re_greeting.match("Good Morn'n Rosa")
<re.Match object; span=(0, 16), match="Good Morn'n Rosa">
>>> re_greeting.match("yo Rosa")
<re.Match object; span=(0, 7), match='yo Rosa'>

A more detailed greeting pattern accepts variants such as “Good morning” and “yo” and captures a following name. It illustrates both the flexibility and the hand tuning involved in rule design. section 1.5.2

Pattern matching also supports other NLP tasks:

  • Information extraction: use compact condition checks to find useful pieces of a natural-language string. section 11.1.1
  • Named entity recognition: use patterns to identify information such as GPS locations, dates, prices, and numbers. section 11.4
  • Sentence segmentation: use punctuation patterns to identify likely sentence boundaries. section 11.2.2
>>> re.split(r'[!.?]+[\s$]+',
...     "Hello World.... Are you there?!?! I'm going to Mars!")
['Hello World', 'Are you there', "I'm going to Mars!"]

This sentence-splitting expression handles several punctuation marks, but consumes the matched sentence-ending punctuation. The final exclamation mark remains because the pattern does not match it in this input. section 11.2.2

A match confirms that text fits a rule, not that the rule has understood it. Typos and unfamiliar phrasing can cause missed matches, while similar meanings may have very different character sequences. Handcrafted patterns are useful for well-specified targets, but broad language coverage requires continued testing and refinement. section 1.5.3 section 1.5.2

How Natural Language Processing in Action, Second Edition covers it

How deep it goes
Works through greeting expressions and capture groups, then applies regular expressions to sentence segmentation.
Examples
Demonstrates greeting and name matches, and splits sentences using punctuation patterns.
What it assumes
Introduces regular-expression examples without requiring prior understanding of them.
What you can do after
Apply pattern matching via Python's re module to recognize greetings and inspect captured groups.
How it connects
Connects regular expressions with intent recognition, named entity recognition, and sentence segmentation.

Also explained in

Compare how 14 books explain pattern matching →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Natural Language Processing in Action, Second Edition. The section links point to the parts of the book it draws on.