正则表达注意事项(二)(1000则)

前言

该节介绍,注意事项。

正文

第一个注意事项是:

^ 不仅表示开头项,还表示非的意思。

比如说我们\D,表示是非数字。

我们可以这样写:

[^0-9] 或者 [^\d]表示非的意思。

第二个是,注意区分\w和\D,\D表示的是非数字,它有很多东西可以匹配。

\w表示的是字母,数字和下划线。

也就是说\w是[_a-z0-9A-Z]的结合体。

那么\W就是[^_a-z0-9A-Z]。

关于^的一个灵活应用,比如说你想要非\w,而且还附加其他条件。

那么你可以这样[^\w@] 这样就不仅非\w而且还非@了。

第三个:\s 匹配的不是空格。
\s 包括:

  1. 空格
  2. 制表符(\t)
    3.换行符(\n)
    4.回车符(\r)

\S对应的是[^ \t\n\r]

值得注意的是\s不包括所有的空白符,空白符还有:
\f 换行符
\h 水平空白符等。。。

第四个:
.并是不是全部的字符。\n或者\n\r不是。为什么这么说呢?
匹配除“\n”之外的任何单个字符。要匹配包括“\n”在内的任何字符,请使用像“(.|\n)”的模式。

THE RIME OF THE ANCYENT MARINERE, IN SEVEN PARTS.

ARGUMENT.

How a Ship having passed the Line was driven by Storms to the cold
Country towards the South Pole; and how from thence she made her course
to the tropical Latitude of the Great Pacific Ocean; and of the strange
things that befell; and in what manner the Ancyent Marinere came back to
his own Country.

I.

1      It is an ancyent Marinere,
2        And he stoppeth one of three:
3      "By thy long grey beard and thy glittering eye
4        "Now wherefore stoppest me?

我用 .* 去匹配,得到的结果是:

共找到 29 处匹配:
THE RIME OF THE ANCYENT MARINERE, IN SEVEN PARTS.


ARGUMENT.


How a Ship having passed the Line was driven by Storms to the cold

我并没有贴出全部的,但是可以说明并不是匹配全部的。
所有我们匹配单词的时候,尽量不要用.,应该是\b\w{7}\b,用\w。

总结

该文后续持续更新,如果有坑的话。

posted @ 2020-04-20 23:16  敖毛毛  阅读(144)  评论(0编辑  收藏  举报