开发者

Regular expressions: what, when and how [closed]

It's difficult to tell what开发者_StackOverflow社区 is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

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:

  1. Matching a single digit:

    \d
    
  2. Matching several consecutive digits (at least one)

    \d+
    
  3. Matching numbers that contain 5 to 9 digits:

    \d{5,7}
    
  4. 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 59

    The 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜