Regular expressions: what, when and how [closed]
I am wondering what is the use of regular expressions, when and how to use them.
Please explain with an example.
Wikipedia article: Regular Expression
Regular expressions are useful in the production of syntax highlighting systems, data validation, and many other tasks.
While regular expressions would be useful on search engines such as Google, processing them across the entire database could consume excessive computer resources depending on the complexity and design of the regex. Although in many cases system administrators can run regex-based queries internally, most search engines do not offer regex support to the public. Notable exceptions: Google Code Search, Exalead.
Example
When you'll finish reading the article you'll be acquainted with basic syntach so you will know that \d
metacharacter matches a digit. In fact matching digits seems to be one of the most common used metacharacters in regularexpressions. If we combine them with others we can match quite complex everyday scenarios:
Matching a single digit:
\d
Matching several consecutive digits (at least one)
\d+
Matching numbers that contain 5 to 9 digits:
\d{5,7}
Matching 24-hour time representation:
(?:[01]?\d|2[0123]):[0-5]\d
The
(?: )
represents a sub regular expression that doesn't get saved (because it has?:
in it) and this sub expression says that a matching string should be either:[01]?\d
which says that a 0 or 1 may be present (hence the question mark) followed by any single digit; this part matches these: 0, 00, 1, 01, ... 0, 09, 10, ... 19- or it may be
2[0123]
which matches 20, 21, 22 and 23
Then we have a
:
(colon) and two digits of which the first one may be 0 to 5 and second one can be any single digit, which matches everything from 00, 01, ... 09, 10, ... to 59The first part represents hours and the second one minutes in 24-hour time notation ie 0:00, 00:24, 2:34, 08:47 or 17:08.
I hope you get the idea and that it wasn't too complicated to understand.
精彩评论