zoukankan      html  css  js  c++  java
  • 正则表达式的语法

    元字符

    我们使用的字符“[”和“]”叫元字符,对模式有特殊的效果。这种元字符共有11个,它们扮演着不同的角色。如果想在建立的模式中包含这些元字符中的某一个字符,需要在该字符前使用转义字符“”。

    元字符

    描述

    开始

    beginning

    字符“^”之后的实体(entity),必须在配匹配的字符串开始部分找到。

    例:

    ^h

    能匹配的字符串:hellohhh

    不能匹配的字符串:characterssh

    结束

    end

    字符“$”之前的实体(entity),必须在配匹配的字符串尾部找到。

    例:

    e$

    能匹配的字符串:sampleefile

    不能匹配的字符串:extrashell

    任何字符

    any

    匹配任何字符。

    例:

    hell.

    能匹配的字符串:hellohellxhell5hell!

    不能匹配的字符串:hellhelo

    [] 

    set

    匹配指定字符集内的任何字符。

    语法:[a-z]表示一个区间,[abcd]表示一组,[a-z0-9]表示两个区间。

    例:

    hell[a-y123]

    能匹配的字符串:hellohell1hell2

    不能匹配的字符串:hellzhell4heloo

    [^ ] 否定组

    negate set

    匹配任何不包括在指定字符集内的字符串

    例:

    hell[^a-np-z0-9]

    能匹配的字符串:hellohell

    不能匹配的字符串:hellahell5

    alternation

    匹配符号“|”之前或之后的实体。

    例:

    hello|welcome

    能匹配的字符串:hellowelcomehelloesawelcome

    不能匹配的字符串:hellellowowelcom

    () 分组

    grouping

    组成一组用于匹配的实体(entity),常用符号“|”协助完成。

    例:

    ^(hello|hi)there$

    能匹配的字符串:hello therehi there

    不能匹配的字符串:hey thereahoy there

     转义

    escape

    允许你对一个特殊字符转义(即将具有特殊意义的字符变为普通的文本字符)

    例:

    hello.

    能匹配的字符串:hello.hello...

    不能匹配的字符串:hellohella

    量词

    可以通过使用有限的字符来表达简单的匹配。下表所示的量词允许你扩展实体匹配使用量词可以定制匹配的次数。

    量词

    描述

    *

    0或多次

    字符“*”之前的实体被发现0次或多次。

    例:

    he*llo

    能匹配的字符串:hllohelloheeeello

    不能匹配的字符串:halloello

    +

    1或多次

    字符“+”之前的实体被发现1次或多次。

    例:

    he+llo

    能匹配的字符串:helloheeello

    不能匹配的字符串:hllohelo

    ?
    01

    字符“?”之前的实体被发现0次或1次。

    例:

    he?llo

    能匹配的字符串:hellohllo

    不能匹配的字符串:heelloheeeello

    {x}

    x

    字符“{}”之前的字符必须匹配指定的x次数。

    例:

    he{3}llo

    能匹配的字符串:heeellooh heeello

    不能匹配的字符串:helloheelloheeeello

    {x,}

    至少x

    字符“{}”之前的字符必须至少出现x次。(即可以多于x次)

    例:

    he{3}llo

    能匹配的字符串:heeelloheeeeello

    不能匹配的字符串:hllohelloheello

    {x,y}

    xy

    字符“{}”之前的字符出现的次数必须介于xy次之间。

    例:

    he{2,4}llo

    能匹配的字符串:heelloheeelloheeeello

    不能匹配的字符串:helloheeeeello

    捕获

    正则表达式机制最后一个功能是能够捕获子表达式,放在“()”之间的任何文本,在被捕获后都能用于后面的匹配处理。

    模式

    字符串

    捕获

    ^(hello|hi)(sir|mister)$

    hello sir

    $1 = hello

    $2 = sir

    ^(.*)$

    nginx rocks

    $1 = nginx rocks

    ^(.{1,3})([0-9]{1,4})([?!]{1,2})$

    abc1234?!

    $1 = abc

    $2 = 1234

    $3 = ?!

  • 相关阅读:
    iaas,paas,saas理解
    July 06th. 2018, Week 27th. Friday
    July 05th. 2018, Week 27th. Thursday
    July 04th. 2018, Week 27th. Wednesday
    July 03rd. 2018, Week 27th. Tuesday
    July 02nd. 2018, Week 27th. Monday
    July 01st. 2018, Week 27th. Sunday
    June 30th. 2018, Week 26th. Saturday
    June 29th. 2018, Week 26th. Friday
    June 28th. 2018, Week 26th. Thursday
  • 原文地址:https://www.cnblogs.com/moqiang02/p/4061247.html
Copyright © 2011-2022 走看看