正则表达式学习

参考网址:https://regexone.com/

image

  • lesson1 使用.匹配任意字符,使用“\”转义“.” ,代表真正意义上的".",而不是通配符

QQ图片20240607125516

  • lesson2 [abc] only a,b or c 中括号

There is a method for matching specific characters using regular expressions, by defining them inside square brackets. For example, the pattern [abc] will only match a single a, b, or c letter and nothing else.

image

  • lesson3 [^abc] 匹配任意非a,b,c

}DXPR{EMW{A454O5}OK89AL

答案也可以是[^b]og ,[hd]og

  • 字符范围

    使用方括号表示法时,可以使用短划线表示字符范围来匹配连续字符列表中的字符。例如,模式[0-6]仅匹配从零到六的任何单个数字字符,而不匹配其他字符。同样,[^np]仅匹配除字母 n 到 p 之外的任何单个字符。

    多个字符范围也可以与单个字符一起在同一组括号中使用。例如,字母数字 \w元字符相当于字符范围 [A-Za-z0-9_] ,通常用于匹配英文文本中的字符。

image

  • 重复 {m} 重复m ,{m,n} 重复m到n

    • 。例如,a{3}将精确匹配 a 字符三次。某些正则表达式引擎甚至允许您指定此重复的范围,例如,a{1,3}将匹配 a 字符不超过 3 次,但不少于 1 次。
      该量词可以与任何字符或特殊元字符一起使用,例如w{3}(三个 w)、[wxy]{5}(五个字符,每个字符可以是 w、x 或 y)和.{2,6}(两个到六个之间的任何字符)。

image

  • *0个或者更多 + 1个或者更多

A powerful concept in regular expressions is the ability to match an arbitrary number of characters. For example, imagine that you wrote a form that has a donation field that takes a numerical value in dollars. A wealthy user may drop by and want to donate undefined.

One way to express such a pattern would be to use what is known as the Kleene Star and the Kleene Plus, which essentially represents either 0 or more or 1 or more of the character that it follows (it always follows a character or group). For example, to match the donations above, we can use the pattern \d* to match any number of digits, but a tighter regular expression would be \d+ which ensures that the input string has at least one digit.

These quantifiers can be used with any character or special metacharacters, for example a+ (one or more a's), [abc]+ (one or more of any a, b, or c character) and .* (zero or more of any character).

image

  • ?(metacharacter)

    • 此元字符允许您匹配零个或一个前面的字符或组。例如,模式ab?c将匹配字符串“abc”或“ac”,因为 b 被视为可选的。
    • 与点元字符类似,问号是一个特殊字符,您必须使用斜杠 ? 对其进行转义,才能匹配字符串中的普通问号字符。

QQ图片20240607133751

  • \s 任意空格键,\S任意非空格键

QQ图片20240607134239

  • ^...$ 开始和结束、

    收紧模式的一种方法是使用特殊的(帽子)和$(美元符号)元字符定义一个描述*行首和行尾的*模式。在上面的例子中,我们可以使用模式success来仅匹配以单词“success”开头的行,而不匹配行“Erro

image

  • 捕获组 (...)
  • //您可以使用诸如^(IMG\d+.png)$之类的模式来捕获和提取完整文件名。
    

QQ图片20240607135820

  • 捕获子组(a(bc))

QQ图片20240607140140

  • 捕获全部(.*)

VYPRE3Q3}8KD(J`D0GF~)7E

  • (abc|def)匹配abc或者def

1b15cf1a-7d6f-4ef7-98b6-4bc2d8d54b51

posted @ 2025-07-24 09:04  晓叔  阅读(11)  评论(0)    收藏  举报