Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Javascript Regular Expressions

You're reading from  Javascript Regular Expressions

Product type Book
Published in May 2015
Publisher
ISBN-13 9781783282258
Pages 112 pages
Edition 1st Edition
Languages
Toc

Grouping, alternation, and back reference


In the following table, you can find the patterns for grouping, alternation, and back reference. The grouping is used to group a set of characters in a Regex. The alternation is used to combine characters into a single regular expression, and the back reference is used to match the same text as previously matched by a capturing group:

Pattern

Description

Example

(x)

This groups characters together to create a clause, that is, it matches x and remembers the match. These are called capturing parentheses.

/(foo)/ matches and remembers "foo" in "foo bar".

()

Parenthesis also serves to capture the desired subpattern within a pattern.

/(\d\d)\/(\d\d)\/(\d\d\d\d)/ matches "12", "12", and "2000" in "12/12/2000".

(?:x)

This matches x but does not capture it. In other words, no numbered references are created for the items within the parenthesis. These are called non-capturing parentheses.

/(?:foo)/ matches, but does not remember "foo" in "foo bar".

|

Alternation combines clauses into one regular expression, and then matches any of the individual clauses. x|y matches either x or y. It is similar to the "OR" statement.

/morning|night/ matches "morning" in "good morning" and matches "night" in "good night".

()\n

"\n" (where n is a number from 1-9) when added to the end of a regular expression pattern, allows you to back reference a subpattern within the pattern, so, the value of the subpattern is remembered and used as part of the matching.

/(no)\1/ matches "nono" in "nono". "\1" is replaced with the value of the first subpattern within the pattern, or (no), to form the final pattern.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime