Groups and Capturing

Group patterns and capture matched text with parentheses

#groups #capturing #backreferences #non-capturing

Groups and Capturing

Use parentheses to group patterns and capture matched text.

Basic Capturing Group

(\d{3})-(\d{4})

Matches: 555-1234

  • Group 1: 555
  • Group 2: 1234

Non-Capturing Group

(?:Mr|Mrs|Ms)\.?\s+([A-Z][a-z]+)

Matches: Mr. Smith, Mrs Jones

  • Doesn't capture title, only captures name

Named Capturing Groups

(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})

Matches: 2025-11-09

  • Named group year: 2025
  • Named group month: 11
  • Named group day: 09

Backreferences

(\w+)\s+\1

Matches repeated words: hello hello, test test

  • \1 refers back to first captured group

Multiple Groups

^(\w+)@(\w+)\.(\w+)$

Matches: user@example.com

  • Group 1: user
  • Group 2: example
  • Group 3: com

Alternation in Groups

(cat|dog|bird)

Matches: cat, dog, or bird

Nested Groups

((Mr|Mrs|Ms)\.?\s+)?([A-Z][a-z]+)

Matches: Mr. Smith or just Smith

  • Group 1: Optional title with space
  • Group 2: Title only
  • Group 3: Last name

Backreference for Quotes

(['"])(.+?)\1

Matches quoted strings with same quote type:

  • "hello"
  • 'world'
  • "mixed'

Conditional Groups

(\d{3})-?(\d{4})

Matches phone numbers with or without dash:

  • 555-1234
  • 5551234

Group for Replacement

When using regex in JavaScript:

const text = "John Smith";
const result = text.replace(/(\w+)\s+(\w+)/, "$2, $1");
// Result: "Smith, John"

Complex Email Pattern with Groups

^(?<username>[a-zA-Z0-9._%+-]+)@(?<domain>[a-zA-Z0-9.-]+)\.(?<tld>[a-zA-Z]{2,})$

Matches: user.name@example.co.uk

  • username: user.name
  • domain: example.co
  • tld: uk

Discover another handy tool from EditPDF.pro