V4if 's Blogwebsite

正则匹配HTML标签

发表于2016-03-27
默认

正则模式匹配HTML标签<tag></tag>,对已经编辑好的静态文本标签进行嵌套包裹处理,比如给<img>包裹上<a></a>,即处理之后的内容为<a href=""><img src=""></a>
正则也是看了总忘,然后借着这篇文章把知识也梳理一下。

起因

Hexo静态博客本地解析的时候图片都解析为<img>标签,经过浏览器渲染之后表现出来的结果就是图片不能点击,也不能进行放大,这样一些比较小的图片在博客里面不太清楚。
<img>标签包裹上<a></a>标签让图片以链接的内容存在。

<a class="post-img-nav" title="" target="_blank" href="http://7xot8c.com1.z0.glb.clouddn.com/zoro.jpeg">
    <img alt="zero" src="http://7xot8c.com1.z0.glb.clouddn.com/zoro.jpeg">
</a>

效果如下图,可以点击图片打开链接
zero

快速参考

正则表达式wiki词条

正则表达式使用单个字符串来描述、匹配一系列符合某个句法规则的字符串。一个正则表达式通常被成为一个模式(pattern),为用来描述或者匹配一系列符合某个句法规则的字符串。例如:Handel、Händel和Haendel这三个字符串,都可以由「H(a|ä|ae)ndel」这个模式来描述。

Regex quick reference

[abc]        A single character: a, b or c
[^abc]      Any single character but a, b, or c
[a-z]       Any single character in the range a-z
[a-zA-Z]    Any single character in the range a-z or A-Z
^           Start of line
$           End of line
\A          Start of string
\z          End of string
.           Any single character
\s          Any whitespace character
\S          Any non-whitespace character
\d          Any digit
\D          Any non-digit
\w          Any word character (letter, number, underscore)
\W          Any non-word character
\b          Any word boundary character
(...)       Capture everything enclosed
(a|b)       a or b
a?          Zero or one of a
a*          Zero or more of a
a+          One or more of a
a{3}        Exactly 3 of a
a{3,}       3 or more of a
a{3,6}      Between 3 and 6 of a

举个例子

以一个邮箱的正则匹配作为例子
e-mail

博客解析代码

ejs模板解析

<div class="article-post">
  <%
     var str = page.content;
     //非贪婪模式
     var reg = /<img\s*src="(.*?)"\s*alt="(.*?)".*?>/g;         
     var replace = '<a class="post-img-nav" href="$1" target="_blank" title=""><img src="$1" alt="$2"></a>';
     var article = str.replace(reg,replace);
  %>
  <%-article %>
</div>