spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / javascript / professional / chap3 / 5 12
[previous]
Developer News
Mandrake Linux Founder Back, Virtually
Amazon: We're a Technology Company
Sun Expands MySQL With Closed Source

Professional JavaScript

RE Syntax - Shortcuts and Options

If you've kept up with this discussion so far, you should have realized that this is not a very flexible system yet. Apart from the wildcard character – a period or full stop – we've yet to proffer any notation that specifies an option on single characters. For example, let's take a brand new string we want to match our regular expressions against.


dink fink link mink oink pink rink sink tink wink +ink _ink "ink

Now, suppose we wished only to match link, mink, and wink from the string above. From what we know currently, the only option we have is to create three regular expressions – one for each word. Using the wildcard in /.ink/ will match every word in the string and that's not what we want.

There is, of course, a solution. By using square braces, [], we can specify which group of letters we want to match a certain character. So then we should use


var RE7 = /[lmw]ink/;       //matches "link", "mink" and "wink"
to get the desired matches. At the same time, we can also use 'not-this-group' [^ ] to match every other word in the string.

var RE8 = /[^lmw]ink/;      //matches "dink", "fink", "oink", "pink", etc
                            //but not "link", "mink" and "wink"

This is all very well if you've got a few characters that you'd like to check in a single space, but when you've got ten or twelve, your RE is going to start looking quite unwieldy (or should that be unwieldier?). Fortunately, we can also specify ranges of characters using the hyphen, -, within the braces as a marker to indicate the range. For example, to match every word apart from tink and wink in the string, you could either of:


var RE9 = /[a-s]ink/;
var RE10 = /[^t-z]ink/;

By now you might have realized that in using a hyphen, [0-9] represents all the numerals, [a-z] the lower case letters and [A-Z] the uppercase. Again, we have some shortcuts for particular ranges of characters that make things more compact.

ShortcutRepresents the range..
\d [0-9] Any number character
\D [^0-9] Any non-number character
\w [0-9a-zA-Z_] Any letter, numeral or underscore
\W [^0-9a-zA-Z_] Any non-alphanumeric character except the underscore
\s [ \f\n\r\t\v] Any whitespace character
\S [^ \f\n\r\t\v] Any non-whitespace character. NB Not the same as \w

There is one more thing to mention in this section - the alternation of the or symbol (|). Equivalent to the or operator in Chapter 1 (remember ||?), the alternation symbol matches any one group of symbols out of several groups specified. For example /(ab|cd)/ will match either two-character sequence. We use the parenthesis to remind ourselves how the two parts of the alternation are related – the use of parentheses here is used to add clarity in the same way that you can use parenthesis in common mathematical expressions. Let's look at some examples.


var RE11 = /^([1-9]|1[0-2]):[0-5]\d$/;      // Matches proper time values
var RE12 = /['"]/d/d/d['"]/;         // Matches a three digit number in quotes
var RE13 = /[123]|[^123]/;           

Our last example, RE13, serves little purpose other than to illustrate the or symbol. In effect, it does the same job as the wildcard character..

RE Syntax - Repetition and References

There are still some limitations to what we can do with regular expressions, the most notable being that we have to write out explicitly how many characters we're searching for in our pattern. This is fine for small, well-defined patterns like example RE11 for matching time strings, but say we wanted to match any string in quotes and you are facing quite a challenge to match it with a group of expressions like RE12.

The solution comes from a number of special characters used to denote the repetition of a letter, number, etc as follows.

Characters Meaning
? Either zero or one match only
* Zero or more matches
+ One or more matches
{n} Exactly n matches
{n,m} No less than n and no more than m matches
{n,} At least n matches

Each of these characters should come directly after the character or group that you wish to denote is repeated as is demonstrated below.


var RE14 = /g?nash/;               //Matches gnash or nash
var RE15 = /g*nash/;               //Matches nash, gnash, ggnash, gggnash etc.
var RE16 = /g+nash/;               //Matches gansh, ggnash, etc but not nash
var RE17 = /go{2}p/;               //Matches goop, not gop or gooop
var RE18 = /go{3,}p/;              //Matches gooop, goooop, not gop or goop
var RE19 = /go{1,3}p/;             //Matches gop, goop and gooop only
var RE20 = /['"][^'"]*['"]/;       //Matches a quoted string of length 0-?

You can also specify a sequence of characters to be repeated by enclosing them in parentheses like so.


var RE21 = /\d{5}(-\d{4})?/;         //Matches zip codes

The use of parentheses brings us on neatly to our final piece of syntax – reference markers. Consider the strings 212-555-212, 628-932-628, "Quote 1" and 'Quote 2'. Each of them has a (series of) character(s) repeated after some others. Regular expressions allow us one more match test on strings – to match character strings against those stored elsewhere in the same string. In effect, we can search for a matching pair of quotes or brackets and subsequently do something with the contents. For example, we can ensure a user's name matches that written on his credit card or, in the case of calculating mathematical pi (p) that no single digit is repeated more than twice in a row. We do this with references.

Let's take the number example. The regular expression to match those numbers mentioned earlier would be /\d{3}-\d{3}-\d{3}/. In order to match the first group of three numbers with the last, we would alter that expression slightly to /(\d{3})-\d{3}-\1/. The new escape sequence here, \1, seeks out the first expression within a set of parentheses and finds out the match for that expression. Then it tries to match a later sequence of characters against that earlier qualifying match.

These reference escape sequences can refer to the nth set of parentheses in a regular expression, so it's not uncommon to see \2, \3, \4 etc in more complex expressions. In the case where the parentheses are nested \n refers to the pair of parentheses that begins with the nth left parentheses starting from the left. One final word of caution here. Should you use, for example \10, in your expression when there are not ten sets of parentheses present, JavaScript will take this as meaning the ASCII character with octal value 10 - in this case, a backspace. There are only 9 maximum matches allowed.

To conclude, regular expressions are built out of pattern matching elements that together form more sophisticated patterns. The pattern matching process takes a candidate string and matches it from left-to-right against the supplied regular expression pattern. If there is any possible match at all, the string matches. If there is no match, you can be sure there is no possible interpretation of the pattern that could work for the string. This is an important point you can rely on if the regular expression, or the string it works on starts becoming complex.

home / programming / javascript / professional / chap3 / 5 12
[previous]

Copyright 1999 (1st Edition) and 2001 (2nd Edition) Wrox Press Ltd. and

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Whitepapers and eBooks

Intel Whitepaper: Comparing Two- and Four-Socket Platforms for Server Virtualization
IBM Solutions Brief: Go Green With IBM System xTM And Intel
HP eBook: Simplifying SQL Server Management
IBM Contest: Are You the Next Superstar? Join the "Search for the XML Superstar" Contest to Find Out
Microsoft PDF: Top 10 Reasons to Move to Server Virtualization with Hyper-V
Microsoft PDF: Six Reasons Why Microsoft's Hyper-V Will Overtake Vmware
Microsoft Step-by-Step Guide: Hyper-V and Failover Clustering
Intel PDF: Quad-Core Impacts More Than the Data Center
Intel PDF: Virtualization Delivers Data Center Efficiency
Go Parallel Article: PDC 2008 in Review
Microsoft PDF: Top 11 Reasons to Upgrade to Windows Server 2008
Avaya Article: Communication-Enabled Mashups: Empowering Both Business Owners and IT
Intel Whitepaper: Building a Real-World Model to Assess Virtualization Platforms
  PDF: Intel Centrino Duo Processor Technology with Intel Core2 Duo Processor
Microsoft Article: Build and Run Virtual Machines with Hyper-V Server 2008
Go Parallel Article: Q&A with a TBB Junkie
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
IBM eBook: The Pros and Cons of Outsourcing
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
HP eBook: Guide to Storage Networking
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
webref The latest from WebReference.com Browse >
Popular JavaScript Framework Libraries: An Overview - Part 3 · Accessing Your MySQL Database from the Web with PHP · Working with the DOM Stylesheets Collection
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Crucial Triples Up With New Three-Channel DDR3 Kits · Meet the Finalists: Excellence in Technology Awards · Tealeaf Offers Insight to Mobile Customer Behavior


Created: February 12, 2001
Revised: February 21, 2001


URL: http://webreference.com/programming/javascript/professional/chap3/