Introduction

Regular Expression is a very important part of any language programming because of its ability to help programmers to write fast and pure applications.

You Don't Know What a Regular Expression Is?

A regular expression is an object that describes a pattern of characters.

Regular expressions are used to perform pattern-matching and "search-and-replace" functions on text.

Web developer can also use Regular Expression in JavaScript. Now I describe some simple examples of using Regular Expression in JavaScript.

The overall syntax should look like:

/pattern/modifiers

  • pattern specifies the search pattern
  • modifiers specify if our search should be case-sensitive, global, etc.

Modifiers Table

Modifier Description
i Perform case-insensitive matching
g Perform a global match (find all matches rather than stopping after the first match)
m Perform multiline matching

To compile and use Regular Expression, you can use three useful functions.

Regular Expression Object Methods

Method Description
compile() Compiles a regular expression
exec() Tests for a match in a string. Returns the first match
test() Tests for a match in a string. Returns true or false

Example

Test sentence: Sometext sometext sometext

Expression Test Result
/sometext/ Sometext sometext sometext
/sometext/i Sometext sometext sometext
/sometext/g Sometext sometext sometext
/sometext/gi Sometext sometext sometext
/some/ Sometext sometext sometext
/some/i Sometext sometext sometext
/some/g Sometext sometext sometext
/some/ig Sometext sometext sometext

It's easy!

In the next article, I will show you Regular Expression performance in some cases and also how to make simple and pure Regular Expressions.

History

  • 19th May, 2011: Initial version
推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架