<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>我想网 &#187; RegEx</title>
	<atom:link href="http://www.iwanna.cn/topics/develope/regex-develope/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.iwanna.cn</link>
	<description></description>
	<lastBuildDate>Sat, 31 Jul 2010 15:12:14 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>检查素数的正则表达式</title>
		<link>http://www.iwanna.cn/archives/2010/07/23/4680/</link>
		<comments>http://www.iwanna.cn/archives/2010/07/23/4680/#comments</comments>
		<pubDate>Fri, 23 Jul 2010 04:14:14 +0000</pubDate>
		<dc:creator>seasun</dc:creator>
				<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[RegEx]]></category>

		<guid isPermaLink="false">http://www.iwanna.cn/?p=4680</guid>
		<description><![CDATA[一般来说，我们会使用正规表达式来做字符串匹配，今天在网上浏览的时候，看到了有人用正则表达式来检查一个数字是否为素数（质数），让我非常感兴趣，这个正则表达式如入所示：
检查素数的正则表达式/^1?$&#124;^(11+?) +$/
要使用这个正规则表达式，你需要把自然数转成多个1的字符串，如：2 要写成 “11”， 3 要写成 “111”, 17 要写成“11111111111111111”，这种工作使用一些脚本语言可以轻松的完成。

一开始我对这个表达式持怀疑态度，但仔细研究了一下这个表达式，发现是非常合理的，下面，让我带你来细细剖析一下是这个表达式的工作原理。
首先，我们看到这个表达式中有“&#124;”，也就是说这个表达式可以分成两个部分：/^1?$/ 和 /^(11+?)\1+$/

第一部分：/^1?$/， 这个部分相信不用我多说了，其表示匹配“非空串”以及字串中不只一个“1”的字符串。
第二部分：/^(11+?)\1+$/，这个部分是整个表达式的关键部分。其可以分成两个部分，(11+?) 和\1+$，前半部很简单了，匹配以“11”开头的并重复0或n个1的字符串，后面的部分意思是把前半部分作为一个字串去匹配还剩下的字符串1次或多次（这句话的意思是——剩余的字串的1的个数要是前面字串1个数的整数倍）。

通过上面的分析，我们知道，第二部分是最重要的，对于第二部分，举几个例子，
示例一：判断自然数8。我们可以知道，8转成我们的格式就是“11111111”，对于(11+?)，其匹配了“11”，于是还剩下“111111”，而\1+$正好匹配了剩下的“111111”，因为，“11”这个模式在“111111”出现了三次，符合模式匹配，返回true。取反（^），所以，得到false，于是这个数不是质数。
示例二：判断自然数11。转成我们需要的格式是“11111111111”（十一个1），对于(11+?)，其匹配了“11”（前两个1），还剩下“111111111”（九个1），而\1+$无 法为“11”匹配那“九个1”，因为“11”这个模式并没有在“九个1”这个串中正好出现N次。于是，我们的正则表达式引擎会尝试下一种方法，先匹配 “111”（前三个1），然后把“111”作为模式去匹配剩下的“11111111”（八个1），很明显，那“八个1”并没有匹配“三个1”多次。所以， 引擎会继续向下尝试……直至返回false。
通过示例二，我们可以得到这样的等价数算算法，正则表达式会匹配这若干个1中有没有出现“二个1”的整数倍，“三个1”的整数倍，“四个1”的整数倍……，而，这正好是我们需要的算素数的算法。现在大家明白了吧。
下面，我们用perl来使用这个正规则表达式不停地输出素数：（关于perl的语法我就不多说了）
perl -e'$&#124;++;(1 x$_)!~/^1?$&#124;^(11+?)\1+$/&#38;&#38;print"$_ "while ++$_'
另外，让我们来举一反三，根据上述的这种方法，我们甚至可以用正则表达式来求证某方式是否有解，如：

二元方程：17x + 12y = 51   判断其是否有解的正则表达式是：^(.*)\1{16}(.*)\2{11}$
三元方程：11x + 2y + 5z = 115 判断其是否有解的正则表达式是：^(.*)\1{10}(.*)\2{1}(.*)\3{4}$

大家不妨自己做做练习，为什么上述的两个正则表达式可以判断方程是否有解。如果无法参透其中的奥妙的话，你可以读读这篇英文文章。

© 我想网 Akon 所有 , 2010. &#124;
永久链接 &#124;
没有评论 &#124;
提交到
Google Reader
鲜果
抓虾


	标签：Algorithm, Algorithm, RegEx, RegEx

	您可能会感兴趣的其他文章
	
	高级正则表达式的重要概念 
	递归－三角数字 
	用PHP数组对百万数据进行排重 
	浅谈递归过程以及递归的优化 
	正则表达式入门 
	排序－选择 
	排序－插入 
	排序－冒泡 
	排序算法汇总 
	常用的正则表达式 



Feed [...]]]></description>
			<content:encoded><![CDATA[<p>一般来说，我们会<strong><a href="http://www.iwanna.cn/archives/2010/07/23/4680/" title="检查素数的正则表达式">使用正规表达式来做字符串匹配</a></strong>，今天在网上浏览的时候，看到了有人用正则表达式来检查一个数字是否为素数（质数），让我非常感兴趣，这个正则表达式如入所示：<br />
<img title="检查素数的正则表达式" src="http://images.uheed.com/iwanna/2010/07/23/regexpr-for-prime-number.jpg" alt="检查素数的正则表达式 | iwanna.cn 我想网" width="450" height="45" />检查素数的正则表达式/^1?$|^(11+?) +$/</p>
<p>要使用这个正规则表达式，你需要把自然数转成多个1的字符串，如：2 要写成 “11”， 3 要写成 “111”, 17 要写成“11111111111111111”，这种工作使用一些脚本语言可以轻松的完成。<br />
<span id="more-4680"></span><br />
一开始我对这个表达式持怀疑态度，但仔细研究了一下这个表达式，发现是非常合理的，下面，让我带你来细细剖析一下是这个表达式的工作原理。</p>
<p>首先，我们看到这个表达式中有“|”，也就是说这个表达式可以分成两个部分：/^1?$/ 和 /^(11+?)\1+$/</p>
<ul>
<li><strong>第一部分：/^1?$/</strong>， 这个部分相信不用我多说了，其表示匹配“非空串”以及字串中不只一个“1”的字符串。</li>
<li><strong>第二部分：/^(11+?)\1+$/</strong>，这个部分是整个表达式的关键部分。其可以分成两个部分，<strong>(11+?)</strong> 和<strong>\1+$</strong>，前半部很简单了，匹配以“11”开头的并重复0或n个1的字符串，后面的部分意思是把前半部分作为一个字串去匹配还剩下的字符串1次或多次（这句话的意思是——剩余的字串的1的个数要是前面字串1个数的整数倍）。</li>
</ul>
<p>通过上面的分析，我们知道，第二部分是最重要的，对于第二部分，举几个例子，</p>
<p><strong>示例一：判断自然数8</strong>。我们可以知道，8转成我们的格式就是“11111111”，对于<strong>(11+?)</strong>，其匹配了“11”，于是还剩下“111111”，而<strong>\1+$</strong>正好匹配了剩下的“111111”，因为，“11”这个模式在“111111”出现了三次，符合模式匹配，返回true。取反（^），所以，得到false，于是这个数不是质数。</p>
<p><strong>示例二：判断自然数11</strong>。转成我们需要的格式是“11111111111”（十一个1），对于<strong>(11+?)</strong>，其匹配了“11”（前两个1），还剩下“111111111”（九个1），而<strong>\1+$</strong>无 法为“11”匹配那“九个1”，因为“11”这个模式并没有在“九个1”这个串中正好出现N次。于是，我们的正则表达式引擎会尝试下一种方法，先匹配 “111”（前三个1），然后把“111”作为模式去匹配剩下的“11111111”（八个1），很明显，那“八个1”并没有匹配“三个1”多次。所以， 引擎会继续向下尝试……直至返回false。</p>
<p>通过示例二，我们可以得到这样的等价数算算法，正则表达式会匹配这若干个1中有没有出现“二个1”的整数倍，“三个1”的整数倍，“四个1”的整数倍……，而，这正好是我们需要的算素数的算法。现在大家明白了吧。</p>
<p>下面，我们用perl来使用这个正规则表达式不停地输出素数：（关于perl的语法我就不多说了）</p>
<pre>perl -e'$|++;(1 x$_)!~/^1?$|^(11+?)\1+$/&amp;&amp;print"$_ "while ++$_'</pre>
<p>另外，让我们来举一反三，根据上述的这种方法，我们甚至可以用正则表达式来求证某方式是否有解，如：</p>
<ul>
<li><strong>二元方程</strong>：17x + 12y = 51   判断其是否有解的正则表达式是：<strong>^</strong><strong>(</strong><strong>.*</strong><strong>)</strong><strong>\1{16}</strong><strong>(</strong><strong>.*</strong><strong>)</strong><strong>\2{11}$</strong></li>
<li><strong>三元方程</strong>：11x + 2y + 5z = 115 判断其是否有解的正则表达式是：<strong>^</strong><strong>(</strong><strong>.*</strong><strong>)</strong><strong>\1{10}</strong><strong>(</strong><strong>.*</strong><strong>)</strong><strong>\2{1}</strong><strong>(</strong><strong>.*</strong><strong>)</strong><strong>\3{4}$</strong></li>
</ul>
<p>大家不妨自己做做练习，为什么上述的两个正则表达式可以判断方程是否有解。如果无法参透其中的奥妙的话，你可以读读这篇<a href="http://blog.stevenlevithan.com/archives/algebra-with-regexes" target="_blank">英文文章</a>。</p>
<hr />
<p>© <a href="http://www.iwanna.cn">我想网</a> Akon 所有 , 2010. |
<a href="http://www.iwanna.cn/archives/2010/07/23/4680/">永久链接</a> |
<a href="http://www.iwanna.cn/archives/2010/07/23/4680/#comments">没有评论</a> |
提交到
<a rel="nofollow" target="_blank" href="http://www.google.com/reader/view/feed/http://www.iwanna.cn/archives/2010/07/23/4680/">Google Reader</a>
<a rel="nofollow" target="_blank" href="http://www.xianguo.com/subscribe.php?url=http://www.iwanna.cn/archives/2010/07/23/4680/">鲜果</a>
<a rel="nofollow" target="_blank" href="http://www.zhuaxia.com/add_channel.php?url=http://www.iwanna.cn/archives/2010/07/23/4680/">抓虾</a>
<hr />
</p>
	标签：<a href="http://www.iwanna.cn/topics/develope/algorithm/" title="Algorithm" rel="tag nofollow">Algorithm</a>, <a href="http://www.iwanna.cn/tags/algorithm/" title="Algorithm" rel="tag nofollow">Algorithm</a>, <a href="http://www.iwanna.cn/tags/regex/" title="RegEx" rel="tag nofollow">RegEx</a>, <a href="http://www.iwanna.cn/topics/develope/regex-develope/" title="RegEx" rel="tag nofollow">RegEx</a><br />

	<h2 class="related_post">您可能会感兴趣的其他文章</h2>
	<ul class="st-related-posts">
	<li><a href="http://www.iwanna.cn/archives/2009/06/02/1652/" title="高级正则表达式的重要概念 (2009年06月2日)">高级正则表达式的重要概念</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/03/31/71/" title="递归－三角数字 (2009年03月31日)">递归－三角数字</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/06/08/3769/" title="用PHP数组对百万数据进行排重 (2010年06月8日)">用PHP数组对百万数据进行排重</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/07/21/4661/" title="浅谈递归过程以及递归的优化 (2010年07月21日)">浅谈递归过程以及递归的优化</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/04/09/318/" title="正则表达式入门 (2009年04月9日)">正则表达式入门</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/03/31/69/" title="排序－选择 (2009年03月31日)">排序－选择</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/03/31/75/" title="排序－插入 (2009年03月31日)">排序－插入</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/03/31/73/" title="排序－冒泡 (2009年03月31日)">排序－冒泡</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/05/03/929/" title="排序算法汇总 (2009年05月3日)">排序算法汇总</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/04/09/321/" title="常用的正则表达式 (2009年04月9日)">常用的正则表达式</a> </li>
</ul>


<p><small>Feed enhanced by <a href='http://planetozh.com/blog/my-projects/wordpress-plugin-better-feed-rss/'>Better Feed</a> from  <a href='http://planetozh.com/blog/'>Ozh</a></small></p>
]]></content:encoded>
			<wfw:commentRss>http://www.iwanna.cn/archives/2010/07/23/4680/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>15个实用的PHP正则表达式</title>
		<link>http://www.iwanna.cn/archives/2010/07/14/4566/</link>
		<comments>http://www.iwanna.cn/archives/2010/07/14/4566/#comments</comments>
		<pubDate>Wed, 14 Jul 2010 13:38:30 +0000</pubDate>
		<dc:creator>seasun</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[RegEx]]></category>

		<guid isPermaLink="false">http://www.iwanna.cn/?p=4566</guid>
		<description><![CDATA[对于开发人员来说，正则表达式是一个非常有用的功能。它提供了 查找，匹配，替换  句子，单词，或者其他格式的字符串。在这篇文章里，我已经编写了15个贼有用的正则表达式，WEB开发人员都应该将它收藏到自己的工具包。
开始使用正则表达式
对初学者来说，正则看起来很难学习和使用。事实上他们并非你想想的那么难，在我们深入掌握正则之前，先迅速看看这些入门基础：

正则表达式语法
正则表达式     将会匹配
foo ——————字符串“foo”
^foo ——————以“foo”开头的字符串
foo$ ——————以“foo”结尾的字符串
^foo$ ——————“foo”开头和结尾，（只能是他自己 ）
[abc]—————— a 或者b 或者c
[a-z] —————— a到z之间任意字母
[^A-Z]——————除了 A-Z这些之外的字符
(gif&#124;jpg)——————“gif”或者 “jpeg”
[a-z]+—————— 一个或者多个 a到z之间任意字母
[0-9.-]—————— 0-9之间任意数字，或者 点 或者 横线
^[a-zA-Z0-9_]{1,}$—————— 至少一个字母数字下划线
([wx])([yz])—————— wy或wz或xy或xz
[^A-Za-z0-9]—————— 字符数字之外的字符
([A-Z]{3}&#124;[0-9]{4})—————— 三个大写字母或者4个数字
php 正则表达式的方法
方法描述：
preg_match() 该函数preg_match按照模式去匹配字符串，如果符合则返回TRUE，否则返回FALSE
preg_match_all() 该函数 preg_match_all() 在字符串中匹配出全部符合模式的字符串.
preg_replace()  该函数与ereg_replace()类似，不同在于它利用匹配的模式去替换输入的参数
preg_split() 该函数与split()类似 不同在于它将与正则表达式匹配的字符当做分割的模式
preg_grep() 该函数preg_grep() 匹配数组中全部元素，返回符合正则表达式的元素组成的数组
preg_quote() 转义正则表达式字符
验证域名
检验一个字符串是否是个有效域名.
$url = &#8220;http://komunitasweb.com/&#8221;;
if  (preg_match(&#8216;/^(http&#124;https&#124;ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i&#8217;,  $url)) {
echo &#8220;Your url is ok.&#8221;;
} else {
echo &#8220;Wrong url.&#8221;;
}
从一个字符串中 突出某个单词
这是一个非常有用的在一个字符串中匹配出某个单词 并且突出它，非常有效的搜索结果
$text [...]]]></description>
			<content:encoded><![CDATA[<p>对于开发人员来说，正则表达式是一个非常有用的功能。它提供了 查找，匹配，替换  句子，单词，或者其他格式的字符串。在这篇文章里，我已经编写了15个贼有用的正则表达式，WEB开发人员都应该将它收藏到自己的工具包。</p>
<p>开始使用正则表达式</p>
<p>对初学者来说，正则看起来很难学习和使用。事实上他们并非你想想的那么难，在我们深入掌握正则之前，先迅速看看这些入门基础：<br />
<span id="more-4566"></span><br />
正则表达式语法<br />
正则表达式     将会匹配<br />
foo ——————字符串“foo”<br />
^foo ——————以“foo”开头的字符串<br />
foo$ ——————以“foo”结尾的字符串<br />
^foo$ ——————“foo”开头和结尾，（只能是他自己 ）<br />
[abc]—————— a 或者b 或者c<br />
[a-z] —————— a到z之间任意字母<br />
[^A-Z]——————除了 A-Z这些之外的字符<br />
(gif|jpg)——————“gif”或者 “jpeg”<br />
[a-z]+—————— 一个或者多个 a到z之间任意字母<br />
[0-9.-]—————— 0-9之间任意数字，或者 点 或者 横线<br />
^[a-zA-Z0-9_]{1,}$—————— 至少一个字母数字下划线<br />
([wx])([yz])—————— wy或wz或xy或xz<br />
[^A-Za-z0-9]—————— 字符数字之外的字符<br />
([A-Z]{3}|[0-9]{4})—————— 三个大写字母或者4个数字</p>
<p><a href="http://www.iwanna.cn/tags/php/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with PHP">php</a> 正则表达式的方法<br />
方法描述：<br />
preg_match() 该函数preg_match按照模式去匹配字符串，如果符合则返回TRUE，否则返回FALSE<br />
preg_match_all() 该函数 preg_match_all() 在字符串中匹配出全部符合模式的字符串.<br />
preg_replace()  该函数与ereg_replace()类似，不同在于它利用匹配的模式去替换输入的参数<br />
preg_split() 该函数与split()类似 不同在于它将与正则表达式匹配的字符当做分割的模式<br />
preg_grep() 该函数preg_grep() 匹配数组中全部元素，返回符合正则表达式的元素组成的数组<br />
preg_quote() 转义正则表达式字符</p>
<p>验证域名<br />
检验一个字符串是否是个有效域名.</p>
<p>$url = &#8220;http://komunitasweb.com/&#8221;;<br />
if  (preg_match(&#8216;/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i&#8217;,  $url)) {<br />
echo &#8220;Your url is ok.&#8221;;<br />
} else {<br />
echo &#8220;Wrong url.&#8221;;<br />
}</p>
<p>从一个字符串中 突出某个单词<br />
这是一个非常有用的在一个字符串中匹配出某个单词 并且突出它，非常有效的搜索结果</p>
<p>$text = &#8220;Sample sentence from KomunitasWeb, <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> has become popular in  web programming. Now we learn <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a>. According to wikipedia, Regular  expressions (abbreviated as <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> or</p>
<p>regexp, with plural forms regexes, regexps, or regexen) are written in a  formal language that can be interpreted by a regular expression  processor&#8221;;<br />
$text = preg_replace(&#8220;/b(<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a>)b/i&#8221;, &#8216;&lt;span  style=&#8221;background:#5fc9f6&#8243;&gt;1&lt;/span&gt;&#8217;, $text);<br />
echo $text;</p>
<p>突出查询结果在你的 WordPress 博客里<br />
就像刚才我说的，上面的那段代码可以很方便的搜索出结果，而这里是一个更好的方式去执行搜索在某个WordPress的博客上<br />
打开你的文件 search.<a href="http://www.iwanna.cn/tags/php/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with PHP">php</a> ，然后找到 方法 the_title() 然后用下面代码替换掉它<br />
echo $title;Now, just before the modified line, add this code:</p>
<p>&lt;?<a href="http://www.iwanna.cn/tags/php/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with PHP">php</a><br />
$title     = get_the_title();<br />
$keys= explode(&#8221; &#8220;,$s);<br />
$title     = preg_replace(&#8216;/(&#8216;.implode(&#8216;|&#8217;, $keys) .&#8217;)/iu&#8217;,<br />
&#8216;&lt;strong&gt;\0&lt;/strong&gt;&#8217;,<br />
$title);<br />
?&gt;Save the search.<a href="http://www.iwanna.cn/tags/php/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with PHP">php</a> file and open style.css. Append the following  line to it:</p>
<p>strong.search-excerpt { background: yellow; }</p>
<p>从HTML文档中获得全部图片<br />
如果你曾经希望去获得某个网页上的全部图片，这段代码就是你需要的，你可以轻松的建立一个图片下载机器人</p>
<p>$images = array();<br />
preg_match_all(&#8216;/(img|src)=(&#8220;|&#8217;)[^"'&gt;]+/i&#8217;, $data, $media);<br />
unset($data);<br />
$data=preg_replace(&#8216;/(img|src)(&#8220;|&#8217;|=&#8221;|=&#8217;)(.*)/i&#8217;,&#8221;$3&#8243;,$media[0]);<br />
foreach($data as $url)<br />
{<br />
$info = pathinfo($url);<br />
if (isset($info['extension']))<br />
{<br />
if (($info['extension'] == &#8216;jpg&#8217;) ||<br />
($info['extension'] == &#8216;jpeg&#8217;) ||<br />
($info['extension'] == &#8216;gif&#8217;) ||<br />
($info['extension'] == &#8216;png&#8217;))<br />
array_push($images, $url);<br />
}<br />
}</p>
<p>删除重复字母<br />
经常重复输入字母? 这个表达式正适合.</p>
<p>$text = preg_replace(&#8220;/s(w+s)1/i&#8221;, &#8220;$1&#8243;, $text);</p>
<p>删除重复的标点<br />
功能同上，但只是面对标点，白白重复的逗号</p>
<p>$text = preg_replace(&#8220;/.+/i&#8221;, &#8220;.&#8221;, $text);</p>
<p>匹配一个<a href="http://www.iwanna.cn/tags/xml/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with XML">XML</a>或者HTML标签<br />
这个简单的函数有两个参数：第一个是你要匹配的标签，第二个是包含<a href="http://www.iwanna.cn/tags/xml/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with XML">XML</a>或HTML的变量，再强调下，这个真的很强大</p>
<p>function get_tag( $tag, $<a href="http://www.iwanna.cn/tags/xml/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with XML">xml</a> ) {<br />
$tag = preg_quote($tag);<br />
preg_match_all(&#8216;{&lt;&#8217;.$tag.&#8217;[^&gt;]*&gt;(.*?)&lt;/&#8217;.$tag.&#8217;&gt;.&#8217;}',<br />
$<a href="http://www.iwanna.cn/tags/xml/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with XML">xml</a>,<br />
$matches,<br />
PREG_PATTERN_ORDER);</p>
<p>return $matches[1];<br />
}</p>
<p>匹配具有属性值的<a href="http://www.iwanna.cn/tags/xml/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with XML">XML</a>或者HTML标签<br />
这个功能和上面的非常相似，但是它允许你匹配的标签内部有属性值，例如你可以轻松匹配 &lt;div id=”header”&gt;</p>
<p>function get_tag( $attr, $value, $<a href="http://www.iwanna.cn/tags/xml/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with XML">xml</a>, $tag=null ) {<br />
if( is_null($tag) )<br />
$tag = &#8216;\w+&#8217;;<br />
else<br />
$tag = preg_quote($tag);</p>
<p>$attr = preg_quote($attr);<br />
$value = preg_quote($value);</p>
<p>$tag_regex = &#8220;/&lt;(&#8220;.$tag.&#8221;)[^&gt;]*$attr\s*=\s*&#8221;.<br />
&#8220;(['\"])$value\\2[^&gt;]*&gt;(.*?)&lt;\/\\1&gt;/&#8221;</p>
<p>preg_match_all($tag_regex,<br />
$<a href="http://www.iwanna.cn/tags/xml/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with XML">xml</a>,<br />
$matches,<br />
PREG_PATTERN_ORDER);</p>
<p>return $matches[3];<br />
}</p>
<p>匹配十六进制颜色值<br />
web开发者的另一个有趣的工具，它允许你匹配和验证十六进制颜色值.</p>
<p>$string = &#8220;#555555&#8243;;<br />
if (preg_match(&#8216;/^#(?:(?:[a-fd]{3}){1,2})$/i&#8217;, $string)) {<br />
echo &#8220;example 6 successful.&#8221;;<br />
}</p>
<p>查找页面 title<br />
这段代码方便查找和打印 网页 &lt;title&gt; 和&lt;/title&gt; 之间的内容</p>
<p>$fp = fopen(&#8220;http://www.catswhocode.com/blog&#8221;,&#8221;r&#8221;);<br />
while (!feof($fp) ){<br />
$page .= fgets($fp, 4096);<br />
}</p>
<p>$titre = eregi(&#8220;&lt;title&gt;(.*)&lt;/title&gt;&#8221;,$page,$regs);<br />
echo $regs[1];<br />
fclose($fp);</p>
<p>解释 Apache 日志<br />
大多数网站使用的都是著名的Apache服务器，如果你的网站也是，那么使用<a href="http://www.iwanna.cn/tags/php/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with PHP">PHP</a>正则表达式解析 apache 服务器日志 怎么样？</p>
<p>//Logs: Apache web server<br />
//Successful hits to HTML files only.  Useful for counting the number of  page views.<br />
&#8216;^((?#client IP or domain name)S+)s+((?#basic  authentication)S+s+S+)s+[((?#date and time)[^]]+)]s+&#8221;(?:GET|POST|HEAD)  ((?#file)/[^ ?"]+?.html?)??((?#parameters)[^ ?"]+)?  HTTP/[0-9.]+&#8221;s+(?#status code)200s+((?#bytes  transferred)[-0-9]+)s+&#8221;((?#referrer)[^"]*)&#8221;s+&#8221;((?#user agent)[^"]*)&#8221;$&#8217;</p>
<p>//Logs: Apache web server<br />
//404 errors only<br />
&#8216;^((?#client IP or domain name)S+)s+((?#basic  authentication)S+s+S+)s+[((?#date and time)[^]]+)]s+&#8221;(?:GET|POST|HEAD)  ((?#file)[^ ?"]+)??((?#parameters)[^ ?"]+)? HTTP/[0-9.]+&#8221;s+(?#status  code)404s+((?#bytes  transferred)[-0-9]+)s+&#8221;((?#referrer)[^"]*)&#8221;s+&#8221;((?#user agent)[^"]*)&#8221;$&#8217;</p>
<p>使用智能引号代替双引号<br />
如果你是一个印刷爱好者，你将喜欢这个允许用智能引号代替双引号的正则表达式，这个正则被WORDPRESS在其内容上使用</p>
<p>preg_replace(&#8216;B&#8221;b([^"x84x93x94rn]+)b&#8221;B&#8217;, &#8216;?1?&#8217;, $text);</p>
<p>检验密码的复杂度<br />
这个正则表达式将检测输入的内容是否包含6个或更多字母，数字，下划线和连字符. 输入必须包含至少一个大写字母，一个小写字母和一个数字</p>
<p>&#8216;A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])[-_a-zA-Z0-9]{6,}z&#8217;</p>
<p>WordPress: 使用正则获得 帖子上的图片<br />
我知道很多人是WORDPRESS的使用者，你可能会喜欢并且愿意使用  那些从帖子的内容检索下来的图像代码。使用这个代码在你的BLOG只需要复制下面代码到你的某个文件里</p>
<p>&lt;?<a href="http://www.iwanna.cn/tags/php/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with PHP">php</a> if (have_posts()) : ?&gt;<br />
&lt;?<a href="http://www.iwanna.cn/tags/php/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with PHP">php</a> while (have_posts()) : the_post(); ?&gt;</p>
<p>&lt;?<a href="http://www.iwanna.cn/tags/php/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with PHP">php</a><br />
$szPostContent = $post-&gt;post_content;<br />
$szSearchPattern = &#8216;~&lt;img [^&gt;]* /&gt;~&#8217;;</p>
<p>// Run preg_match_all to grab all the images and save the results in  $aPics<br />
preg_match_all( $szSearchPattern, $szPostContent, $aPics );</p>
<p>// Check to see if we have at least 1 image<br />
$iNumberOfPics = count($aPics[0]);</p>
<p>if ( $iNumberOfPics &gt; 0 ) {<br />
// Now here you would do whatever you need to do with the images<br />
// For this example the images are just displayed<br />
for ( $i=0; $i &lt; $iNumberOfPics ; $i++ ) {<br />
echo $aPics[0][$i];<br />
};<br />
};</p>
<p>endwhile;<br />
endif;<br />
?&gt;</p>
<p>自动生成笑脸图案<br />
被WordPress使用的另一个方法, 这段代码可使你把图像自动更换一个笑脸符号</p>
<p>$texte=&#8217;A text with a smiley  &#8216;;<br />
echo str_replace(&#8216;:-)&#8217;,'&lt;img src=&#8221;smileys/souriant.png&#8221;&gt;&#8217;,$texte);</p>
<hr />
<p>© <a href="http://www.iwanna.cn">我想网</a> Akon 所有 , 2010. |
<a href="http://www.iwanna.cn/archives/2010/07/14/4566/">永久链接</a> |
<a href="http://www.iwanna.cn/archives/2010/07/14/4566/#comments">没有评论</a> |
提交到
<a rel="nofollow" target="_blank" href="http://www.google.com/reader/view/feed/http://www.iwanna.cn/archives/2010/07/14/4566/">Google Reader</a>
<a rel="nofollow" target="_blank" href="http://www.xianguo.com/subscribe.php?url=http://www.iwanna.cn/archives/2010/07/14/4566/">鲜果</a>
<a rel="nofollow" target="_blank" href="http://www.zhuaxia.com/add_channel.php?url=http://www.iwanna.cn/archives/2010/07/14/4566/">抓虾</a>
<hr />
</p>
	标签：<a href="http://www.iwanna.cn/topics/develope/php/" title="PHP" rel="tag nofollow">PHP</a>, <a href="http://www.iwanna.cn/tags/php/" title="PHP" rel="tag nofollow">PHP</a>, <a href="http://www.iwanna.cn/tags/regex/" title="RegEx" rel="tag nofollow">RegEx</a>, <a href="http://www.iwanna.cn/topics/develope/regex-develope/" title="RegEx" rel="tag nofollow">RegEx</a><br />

	<h2 class="related_post">您可能会感兴趣的其他文章</h2>
	<ul class="st-related-posts">
	<li><a href="http://www.iwanna.cn/archives/2009/07/05/1936/" title="PHP用正则表达式解析 XML (2009年07月5日)">PHP用正则表达式解析 XML</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/08/27/2195/" title="PHP正则表达式常用范例 (2009年08月27日)">PHP正则表达式常用范例</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/09/11/2233/" title="PHP中用正则表达式验证中文 (2009年09月11日)">PHP中用正则表达式验证中文</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/06/02/1652/" title="高级正则表达式的重要概念 (2009年06月2日)">高级正则表达式的重要概念</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/04/02/149/" title="设计模式之单例模式 (2009年04月2日)">设计模式之单例模式</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/07/31/2088/" title="论述PHP开发框架: What, When, Why and Which? (2009年07月31日)">论述PHP开发框架: What, When, Why and Which?</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/06/08/3767/" title="腾讯PHP程序员面试题目 (2010年06月8日)">腾讯PHP程序员面试题目</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/04/03/171/" title="简易Wordpress模板代码帮助手册中文版 (2009年04月3日)">简易Wordpress模板代码帮助手册中文版</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/06/08/3769/" title="用PHP数组对百万数据进行排重 (2010年06月8日)">用PHP数组对百万数据进行排重</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/07/05/1933/" title="用 PHP 读取和编写 XML DOM (2009年07月5日)">用 PHP 读取和编写 XML DOM</a> </li>
</ul>


<p><small>Feed enhanced by <a href='http://planetozh.com/blog/my-projects/wordpress-plugin-better-feed-rss/'>Better Feed</a> from  <a href='http://planetozh.com/blog/'>Ozh</a></small></p>
]]></content:encoded>
			<wfw:commentRss>http://www.iwanna.cn/archives/2010/07/14/4566/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP中用正则表达式验证中文</title>
		<link>http://www.iwanna.cn/archives/2009/09/11/2233/</link>
		<comments>http://www.iwanna.cn/archives/2009/09/11/2233/#comments</comments>
		<pubDate>Fri, 11 Sep 2009 05:16:45 +0000</pubDate>
		<dc:creator>seasun</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[RegEx]]></category>

		<guid isPermaLink="false">http://www.iwanna.cn/?p=2233</guid>
		<description><![CDATA[str = &#8216;中华人民共和国123456789abcdefg&#8217;;
echo preg_match(&#8220;/^[\u4e00-\u9fa5_a-zA-Z0-9]{3,15}&#8221;,strName);
运行一下上面这段代码，看会有什么提示信息？
Warning: preg_match(): Compilation failed: PCRE does not support \L, \l, \N, \P, \p, \U, \u, or \X at offset 3 in F:\wwwroot\php\test.php on line 2
原来，PHP正则表达式中不支持下列 Perl 转义序列：\L, \l, \N, \P, \p, \U, \u, or \X
在 UTF-8 模式下，允许用“\x{&#8230;}”，花括号中的内容是表示十六进制数字的字符串。原来的十六进制转义序列 \xhh 如果其值大于 127 的话则匹配了一个双字节 UTF-8 字符。
所以，可以这样来解决preg_match(&#8220;/^[\x80-\xff_a-zA-Z0-9]{3,15}&#8221;,strName);

© 我想网 Akon 所有 , 2009. &#124;
永久链接 &#124;
没有评论 &#124;
提交到
Google Reader
鲜果
抓虾


	标签：PHP, [...]]]></description>
			<content:encoded><![CDATA[<p>str = &#8216;中华人民共和国123456789abcdefg&#8217;;<br />
echo preg_match(&#8220;/^[\u4e00-\u9fa5_a-zA-Z0-9]{3,15}&#8221;,strName);</p>
<p>运行一下上面这段代码，看会有什么提示信息？<br />
Warning: preg_match(): Compilation failed: PCRE does not support \L, \l, \N, \P, \p, \U, \u, or \X at offset 3 in F:\wwwroot\<a href="http://www.iwanna.cn/tags/php/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with PHP">php</a>\test.<a href="http://www.iwanna.cn/tags/php/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with PHP">php</a> on line 2</p>
<p>原来，<a href="http://www.iwanna.cn/tags/php/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with PHP">PHP</a>正则表达式中不支持下列 Perl 转义序列：\L, \l, \N, \P, \p, \U, \u, or \X</p>
<p>在 UTF-8 模式下，允许用“\x{&#8230;}”，花括号中的内容是表示十六进制数字的字符串。原来的十六进制转义序列 \xhh 如果其值大于 127 的话则匹配了一个双字节 UTF-8 字符。<br />
所以，可以这样来解决preg_match(&#8220;/^[\x80-\xff_a-zA-Z0-9]{3,15}&#8221;,strName);</p>
<hr />
<p>© <a href="http://www.iwanna.cn">我想网</a> Akon 所有 , 2009. |
<a href="http://www.iwanna.cn/archives/2009/09/11/2233/">永久链接</a> |
<a href="http://www.iwanna.cn/archives/2009/09/11/2233/#comments">没有评论</a> |
提交到
<a rel="nofollow" target="_blank" href="http://www.google.com/reader/view/feed/http://www.iwanna.cn/archives/2009/09/11/2233/">Google Reader</a>
<a rel="nofollow" target="_blank" href="http://www.xianguo.com/subscribe.php?url=http://www.iwanna.cn/archives/2009/09/11/2233/">鲜果</a>
<a rel="nofollow" target="_blank" href="http://www.zhuaxia.com/add_channel.php?url=http://www.iwanna.cn/archives/2009/09/11/2233/">抓虾</a>
<hr />
</p>
	标签：<a href="http://www.iwanna.cn/topics/develope/php/" title="PHP" rel="tag nofollow">PHP</a>, <a href="http://www.iwanna.cn/tags/php/" title="PHP" rel="tag nofollow">PHP</a>, <a href="http://www.iwanna.cn/tags/regex/" title="RegEx" rel="tag nofollow">RegEx</a>, <a href="http://www.iwanna.cn/topics/develope/regex-develope/" title="RegEx" rel="tag nofollow">RegEx</a><br />

	<h2 class="related_post">您可能会感兴趣的其他文章</h2>
	<ul class="st-related-posts">
	<li><a href="http://www.iwanna.cn/archives/2009/07/05/1936/" title="PHP用正则表达式解析 XML (2009年07月5日)">PHP用正则表达式解析 XML</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/08/27/2195/" title="PHP正则表达式常用范例 (2009年08月27日)">PHP正则表达式常用范例</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/07/14/4566/" title="15个实用的PHP正则表达式 (2010年07月14日)">15个实用的PHP正则表达式</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/06/02/1652/" title="高级正则表达式的重要概念 (2009年06月2日)">高级正则表达式的重要概念</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/04/02/149/" title="设计模式之单例模式 (2009年04月2日)">设计模式之单例模式</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/07/31/2088/" title="论述PHP开发框架: What, When, Why and Which? (2009年07月31日)">论述PHP开发框架: What, When, Why and Which?</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/06/08/3767/" title="腾讯PHP程序员面试题目 (2010年06月8日)">腾讯PHP程序员面试题目</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/04/03/171/" title="简易Wordpress模板代码帮助手册中文版 (2009年04月3日)">简易Wordpress模板代码帮助手册中文版</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/06/08/3769/" title="用PHP数组对百万数据进行排重 (2010年06月8日)">用PHP数组对百万数据进行排重</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/07/05/1933/" title="用 PHP 读取和编写 XML DOM (2009年07月5日)">用 PHP 读取和编写 XML DOM</a> </li>
</ul>


<p><small>Feed enhanced by <a href='http://planetozh.com/blog/my-projects/wordpress-plugin-better-feed-rss/'>Better Feed</a> from  <a href='http://planetozh.com/blog/'>Ozh</a></small></p>
]]></content:encoded>
			<wfw:commentRss>http://www.iwanna.cn/archives/2009/09/11/2233/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP正则表达式常用范例</title>
		<link>http://www.iwanna.cn/archives/2009/08/27/2195/</link>
		<comments>http://www.iwanna.cn/archives/2009/08/27/2195/#comments</comments>
		<pubDate>Thu, 27 Aug 2009 04:37:25 +0000</pubDate>
		<dc:creator>seasun</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[RegEx]]></category>

		<guid isPermaLink="false">http://www.iwanna.cn/?p=2195</guid>
		<description><![CDATA[The regular expression, as a pattern, can match all kinds of text strings helping your application validate, compare, compute, decide etc. It can do simple or very complex string manipulations. The list of possibilities is enormous when it comes to what you can achieve using regular expressions. You can take any phrase that starts with [...]]]></description>
			<content:encoded><![CDATA[<p>The regular expression, as a pattern, can match all kinds of text strings helping your application validate, compare, compute, decide etc. It can do simple or very complex string manipulations. The list of possibilities is enormous when it comes to what you can achieve using regular expressions. You can take any phrase that starts with an &#8220;A&#8221; or any character and do various things with it. You can match phone numbers, email addresses, url&#8217;s, credit card numbers, social security numbers, zip codes, states, cities&#8230;..(the list never ends). A huge script that is supposed to validate a user input and prepare it for sql can be reduced to only one line with the help of preg_replace.</p>
<div style="margin-right: 10px;"><a rel="nofollow" href="http://www.amazon.com/gp/product/0596528124?ie=UTF8&amp;tag=findphpajaxas-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0596528124" target="_blank"><img style="border: 0px none ;" src="http://www.roscripts.com/uploads/galleries/mre.gif" alt="mre" /></a></div>
<div style="margin-bottom: 8px;"><a rel="nofollow" href="http://www.amazon.com/gp/product/0596528124?ie=UTF8&amp;tag=findphpajaxas-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0596528124" target="_blank">Mastering Regular Expressions</a></div>
<p>Mastering Regular Expressions quickly covers the basics of regular-expression syntax, then delves into the mechanics of expression-processing, common pitfalls, performance issues, and implementation-specific differences. Written in an engaging style and sprinkled with solutions to complex real-world problems, MRE offers a wealth information that you use. I will start with some simple usage examples of the regular expressions and continue with a huge list of cases for various situations where we would normally need a <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> to operate. We will use simple functions which return TRUE or FALSE. $<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> will serve as our regular expression to match against and $text will be our text (pretty obvious):<br />
<span id="more-2195"></span></p>
<pre>function do_reg($text, $<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a>)
{
	if (preg_match($<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a>, $text)) {
		return TRUE;
	}
	else {
		return FALSE;
	}
}</pre>
<p>The next function will get the part of a given string ($text) matched by the <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> ($<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a>) using a group srorage ($regs). By changing the $regs[0] to $regs[1] we can use a capturing group (in this case griup 1) to match against. The capturing group can also have a name ($regs['groupname']):</p>
<pre>function do_reg($text, $<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a>, $regs)
{
	if (preg_match($<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a>, $text, $regs)) {
		$result = $regs[0];
	}
	else {
		$result = "";
	}
	return $result;
}</pre>
<p>The following function will return an array of all <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> matches in a given string ($text):</p>
<pre>function do_reg($text, $<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a>)
{
	preg_match_all($<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a>, $text, $result, PREG_PATTERN_ORDER);
	return $result = $result[0];
}</pre>
<p>Next we can iterate (loop) over all matches in a string ($text) and output the results:</p>
<pre>function do_reg($text, $<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a>)
{
	preg_match_all($<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a>, $text, $result, PREG_PATTERN_ORDER);
	for ($i = 0; $i &lt; count($result[0]); $i++) {
	$result[0][$i];
}
}</pre>
<p>Extending the above one we can iterate over all matches ($text) and capture groups in a string ($text):</p>
<pre>function do_reg($text, $<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a>)
{
	preg_match_all($<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a>, $text, $result, PREG_SET_ORDER);
	for ($matchi = 0; $matchi &lt; count($result); $matchi++) {
		for ($backrefi = 0; $backrefi &lt; count($result[$matchi]); $backrefi++) {
			$result[$matchi][$backrefi];
		}
	}
}
}</pre>
<p><strong>REGULAR EXPRESSION EXAMPLES BY SITUATIONS AND NEEDS:</strong> <span style="text-decoration: underline;">Addresses</span></p>
<pre>//Address: State code (US)
'/\\b(?:A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])\\b/'

//Address: ZIP code (US)
'\b[0-9]{5}(?:-[0-9]{4})?\b'</pre>
<p><span style="text-decoration: underline;">Columns</span></p>
<pre>//Columns: Match a <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> starting at a specific column on a line.
'^.{%SKIPAMOUNT%}(%<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">REGEX</a>%)'

//Columns: Range of characters on a line, captured into backreference 1
//Iterate over all matches to extract a column of text from a file
//E.g. to grab the characters in colums 8..10, set SKIPAMOUNT to 7, and CAPTUREAMOUNT to 3
'^.{%SKIPAMOUNT%}(.{%CAPTUREAMOUNT%})'</pre>
<p><span style="text-decoration: underline;">Credit cards</span></p>
<pre>//Credit card: All major cards
'^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$'

//Credit card: American Express
'^3[47][0-9]{13}$'

//Credit card: Diners Club
'^3(?:0[0-5]|[68][0-9])[0-9]{11}$'

//Credit card: Discover
'^6011[0-9]{12}$'

//Credit card: MasterCard
'^5[1-5][0-9]{14}$'

//Credit card: Visa
'^4[0-9]{12}(?:[0-9]{3})?$'

//Credit card: remove non-digits
'/[^0-9]+/'</pre>
<p><span style="text-decoration: underline;">CSV</span></p>
<pre>//CSV: Change delimiter
//Changes the delimiter from a comma into a tab.
//The capturing group makes sure delimiters inside double-quoted entries are ignored.
'("[^"\r\n]*")?,(?![^",\r\n]*"$)'

//CSV: Complete row, all fields.
//Match complete rows in a comma-delimited file that has 3 fields per row,
//capturing each field into a backreference.
//To match CSV rows with more or fewer fields, simply duplicate or delete the capturing groups.
'^("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*)$'

//CSV: Complete row, certain fields.
//Set %SKIPLEAD% to the number of fields you want to skip at the start, and %SKIPTRAIL% to
//the number of fields you want to ignore at the end of each row.
//This <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> captures 3 fields into backreferences.  To capture more or fewer fields,
//simply duplicate or delete the capturing groups.
'^(?:(?:"[^"\r\n]*"|[^,\r\n]*),){%SKIPLEAD%}("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*)(?:(?:"[^"\r\n]*"|[^,\r\n]*),){%SKIPTRAIL%}$'

//CSV: Partial row, certain fields
//Match the first SKIPLEAD+3 fields of each rows in a comma-delimited file that has SKIPLEAD+3
//or more fields per row.  The 3 fields after SKIPLEAD are each captured into a backreference.
//All other fields are ignored.  Rows that have less than SKIPLEAD+3 fields are skipped.
//To capture more or fewer fields, simply duplicate or delete the capturing groups.
'^(?:(?:"[^"\r\n]*"|[^,\r\n]*),){%SKIPLEAD%}("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*)'

//CSV: Partial row, leading fields
//Match the first 3 fields of each rows in a comma-delimited file that has 3 or more fields per row.
//The first 3 fields are each captured into a backreference.  All other fields are ignored.
//Rows that have less than 3 fields are skipped.  To capture more or fewer fields,
//simply duplicate or delete the capturing groups.
'^("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*)'

//CSV: Partial row, variable leading fields
//Match the first 3 fields of each rows in a comma-delimited file.
//The first 3 fields are each captured into a backreference.
//All other fields are ignored.  If a row has fewer than 3 field, some of the backreferences
//will remain empty.  To capture more or fewer fields, simply duplicate or delete the capturing groups.
//The question mark after each group makes that group optional.
'^("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*)?,("[^"\r\n]*"|[^,\r\n]*)?'</pre>
<p><span style="text-decoration: underline;">Dates</span></p>
<pre>//Date d/m/yy and dd/mm/yyyy
//1/1/00 through 31/12/99 and 01/01/1900 through 31/12/2099
//Matches invalid dates such as February 31st
'\b(0?[1-9]|[12][0-9]|3[01])[- /.](0?[1-9]|1[012])[- /.](19|20)?[0-9]{2}\b'

//Date dd/mm/yyyy
//01/01/1900 through 31/12/2099
//Matches invalid dates such as February 31st
'(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)[0-9]{2}'

//Date m/d/y and mm/dd/yyyy
//1/1/99 through 12/31/99 and 01/01/1900 through 12/31/2099
//Matches invalid dates such as February 31st
//Accepts dashes, spaces, forward slashes and dots as date separators
'\b(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2}\b'

//Date mm/dd/yyyy
//01/01/1900 through 12/31/2099
//Matches invalid dates such as February 31st
'(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}'

//Date yy-m-d or yyyy-mm-dd
//00-1-1 through 99-12-31 and 1900-01-01 through 2099-12-31
//Matches invalid dates such as February 31st
'\b(19|20)?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])\b'

//Date yyyy-mm-dd
//1900-01-01 through 2099-12-31
//Matches invalid dates such as February 31st
'(19|20)[0-9]{2}[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])'</pre>
<p><span style="text-decoration: underline;">Delimiters</span></p>
<pre>//Delimiters: Replace commas with tabs
//Replaces commas with tabs, except for commas inside double-quoted strings
'((?:"[^",]*+")|[^,]++)*+,'</pre>
<p><span style="text-decoration: underline;">Email addresses</span></p>
<pre>//Email address
//Use this version to seek out email addresses in random documents and texts.
//Does not match email addresses using an IP address instead of a domain name.
//Does not match email addresses on new-fangled top-level domains with more than 4 letters such as .museum.
//Including these increases the risk of false positives when applying the <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> to random documents.
'\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b'

//Email address (anchored)
//Use this anchored version to check if a valid email address was entered.
//Does not match email addresses using an IP address instead of a domain name.
//Does not match email addresses on new-fangled top-level domains with more than 4 letters such as .museum.
//Requires the "case insensitive" option to be ON.
'^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$'

//Email address (anchored; no consecutive dots)
//Use this anchored version to check if a valid email address was entered.
//Improves on the <a href="http://www.iwanna.cn/tags/original/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Original">original</a> email address <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> by excluding addresses with consecutive dots such as john@aol...com
//Does not match email addresses using an IP address instead of a domain name.
//Does not match email addresses on new-fangled top-level domains with more than 4 letters such as .museum.
//Including these increases the risk of false positives when applying the <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> to random documents.
'^[A-Z0-9._%-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$'

//Email address (no consecutive dots)
//Use this version to seek out email addresses in random documents and texts.
//Improves on the <a href="http://www.iwanna.cn/tags/original/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Original">original</a> email address <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> by excluding addresses with consecutive dots such as john@aol...com
//Does not match email addresses using an IP address instead of a domain name.
//Does not match email addresses on new-fangled top-level domains with more than 4 letters such as .museum.
//Including these increases the risk of false positives when applying the <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> to random documents.
'\b[A-Z0-9._%-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b'

//Email address (specific TLDs)
//Does not match email addresses using an IP address instead of a domain name.
//Matches all country code top level domains, and specific common top level domains.
'^[A-Z0-9._%-]+@[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|biz|info|name|aero|biz|info|jobs|museum|name)$'

//Email address: Replace with HTML link
'\b(?:mailto:)?([A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4})\b'</pre>
<p><span style="text-decoration: underline;">HTML</span></p>
<pre>//HTML comment
'&lt;!--.*?--&gt;'

//HTML file
//Matches a complete HTML file.  Place round brackets around the .*? parts you want to extract from the file.
//Performance will be terrible on HTML files that miss some of the tags
//(and thus won't be matched by this regular expression).  Use the atomic version instead when your search
//includes such files (the atomic version will also fail invalid files, but much faster).
'&lt;html&gt;.*?&lt;head&gt;.*?&lt;title&gt;.*?&lt;/title&gt;.*?&lt;/head&gt;.*?&lt;body[^&gt;]*&gt;.*?&lt;/body&gt;.*?&lt;/html&gt;'

//HTML file (atomic)
//Matches a complete HTML file.  Place round brackets around the .*? parts you want to extract from the file.
//Atomic grouping maintains the regular expression's performance on invalid HTML files.
'&lt;html&gt;(?&gt;.*?&lt;head&gt;)(?&gt;.*?&lt;title&gt;)(?&gt;.*?&lt;/title&gt;)(?&gt;.*?&lt;/head&gt;)(?&gt;.*?&lt;body[^&gt;]*&gt;)(?&gt;.*?&lt;/body&gt;).*?&lt;/html&gt;'

//HTML tag
//Matches the opening and closing pair of whichever HTML tag comes next.
//The name of the tag is stored into the first capturing group.
//The text between the tags is stored into the second capturing group.
'&lt;([A-Z][A-Z0-9]*)[^&gt;]*&gt;(.*?)&lt;/\1&gt;'

//HTML tag
//Matches the opening and closing pair of a specific HTML tag.
//Anything between the tags is stored into the first capturing group.
//Does NOT properly match tags nested inside themselves.
'&lt;%TAG%[^&gt;]*&gt;(.*?)&lt;/%TAG%&gt;'

//HTML tag
//Matches any opening or closing HTML tag, without its contents.
'&lt;/?[a-z][a-z0-9]*[^&lt;&gt;]*&gt;'

<span style="text-decoration: underline;">IP addresses</span>
<pre>//IP address
//Matches 0.0.0.0 through 999.999.999.999
//Use this fast and simple <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> if you know the data does not contain invalid IP addresses.
'\b([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\b'

//IP address
//Matches 0.0.0.0 through 999.999.999.999
//Use this fast and simple <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> if you know the data does not contain invalid IP addresses,
//and you don't need access to the individual IP numbers.
'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b'

//IP address
//Matches 0.0.0.0 through 255.255.255.255
//Use this <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> to match IP numbers with accurracy, without access to the individual IP numbers.
'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'

//IP address
//Matches 0.0.0.0 through 255.255.255.255
//Use this <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> to match IP numbers with accurracy.
//Each of the 4 numbers is stored into a capturing group, so you can access them for further processing.
'\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'</pre>
<p><span style="text-decoration: underline;">Lines</span></p>
<pre>//Lines: Absolutely blank (no whitespace)
//<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">Regex</a> match does not include line break after the line.
'^$'

//Lines: Blank (may contain whitespace)
//<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">Regex</a> match does not include line break after the line.
'^[ \t]*$'

//Lines: Delete absolutely blank lines
//<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">Regex</a> match includes line break after the line.
'^\r?\n'

//Lines: Delete blank lines
//<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">Regex</a> match includes line break after the line.
'^[ \t]*$\r?\n'

//Lines: Delete duplicate lines
//This <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> matches two or more lines, each identical to the first line.
//It deletes all of them, except the first.
'^(.*)(\r?\n\1)+$'

//Lines: Truncate a line after a <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> match.
//The <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> you specify is guaranteed to match only once on each line.
//If the <a href="http://www.iwanna.cn/tags/original/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Original">original</a> <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> you specified should match more than once,
//the line will be truncated after the last match.
preg_replace('^.*(%<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">REGEX</a>%)(.*)$', '$1$2', $text);

//Lines: Truncate a line before a <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> match.
//If the <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> matches more than once on the same line, everything before the last match is deleted.
preg_replace('^.*(%<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">REGEX</a>%)', '$1', $text);

//Lines: Truncate a line before and after a <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> match.
//This will delete everything from the line not matched by the regular expression.
preg_replace('^.*(%<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">REGEX</a>%).*$', '$1', $text);</pre>
<p><span style="text-decoration: underline;">Logs</span></p>
<pre>//Logs: Apache web server
//Successful hits to HTML files only.  Useful for counting the number of page views.
'^((?#client IP or domain name)\S+)\s+((?#basic authentication)\S+\s+\S+)\s+\[((?#date and time)[^]]+)\]\s+"(?:GET|POST|HEAD) ((?#file)/[^ ?"]+?\.html?)\??((?#parameters)[^ ?"]+)? HTTP/[0-9.]+"\s+(?#status code)200\s+((?#bytes transferred)[-0-9]+)\s+"((?#referrer)[^"]*)"\s+"((?#user agent)[^"]*)"$'

//Logs: Apache web server
//404 errors only
'^((?#client IP or domain name)\S+)\s+((?#basic authentication)\S+\s+\S+)\s+\[((?#date and time)[^]]+)\]\s+"(?:GET|POST|HEAD) ((?#file)[^ ?"]+)\??((?#parameters)[^ ?"]+)? HTTP/[0-9.]+"\s+(?#status code)404\s+((?#bytes transferred)[-0-9]+)\s+"((?#referrer)[^"]*)"\s+"((?#user agent)[^"]*)"$'</pre>
<p><span style="text-decoration: underline;">Numbers</span></p>
<pre>//Number: Currency amount
//Optional thousands separators; optional two-digit fraction
'\b[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?\b'

//Number: Currency amount
//Optional thousands separators; mandatory two-digit fraction
'\b[0-9]{1,3}(?:,?[0-9]{3})*\.[0-9]{2}\b'

//Number: floating point
//Matches an integer or a floating point number with mandatory integer part.  The sign is optional.
'[-+]?\b[0-9]+(\.[0-9]+)?\b'

//Number: floating point
//Matches an integer or a floating point number with optional integer part.  The sign is optional.
'[-+]?\b[0-9]*\.?[0-9]+\b'

//Number: hexadecimal (C-style)
'\b0[xX][0-9a-fA-F]+\b'

//Number: Insert thousands separators
//Replaces 123456789.00 with 123,456,789.00
'(?&lt;=[0-9])(?=(?:[0-9]{3})+(?![0-9]))'

//Number: integer
//Will match 123 and 456 as separate integer numbers in 123.456
'\b\d+\b'

//Number: integer
//Does not match numbers like 123.456
'(?&lt;!\S)\d++(?!\S)'

//Number: integer with optional sign
'[-+]?\b\d+\b'

//Number: scientific floating point
//Matches an integer or a floating point number.
//Integer and fractional parts are both optional.
'[-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?'

//Number: scientific floating point
//Matches an integer or a floating point number with optional integer part.
//Both the sign and exponent are optional.
'[-+]?\b[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?\b'</pre>
<p><span style="text-decoration: underline;">Passwords</span></p>
<pre>//Password complexity
//Tests if the input consists of 6 or more letters, digits, underscores and hyphens.
//The input must contain at least one upper case letter, one lower case letter and one digit.
'\A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])[-_a-zA-Z0-9]{6,}\z'

//Password complexity
//Tests if the input consists of 6 or more characters.
//The input must contain at least one upper case letter, one lower case letter and one digit.
'\A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])\S{6,}\z'</pre>
<p><span style="text-decoration: underline;">File paths</span></p>
<pre>//Path: Windows
'\b[a-z]:\\[^/:*?"&lt;&gt;|\r\n]*'

//Path: Windows
//Different elements of the path are captured into backreferences.
'\b((?#drive)[a-z]):\\((?#folder)[^/:*?"&lt;&gt;|\r\n]*\\)?((?#file)[^\\/:*?"&lt;&gt;|\r\n]*)'

//Path: Windows or UNC
'(?:(?#drive)\b[a-z]:|\\\\[a-z0-9]+)\\[^/:*?"&lt;&gt;|\r\n]*'

//Path: Windows or UNC
//Different elements of the path are captured into backreferences.
'((?#drive)\b[a-z]:|\\\\[a-z0-9]+)\\((?#folder)[^/:*?"&lt;&gt;|\r\n]*\\)?((?#file)[^\\/:*?"&lt;&gt;|\r\n]*)'</pre>
<p><span style="text-decoration: underline;">Phone numbers</span></p>
<pre>//Phone Number (North America)
//Matches 3334445555, 333.444.5555, 333-444-5555, 333 444 5555, (333) 444 5555 and all combinations thereof.
//Replaces all those with (333) 444-5555
preg_replace('\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})', '(\1) \2-\3', $text);

//Phone Number (North America)
//Matches 3334445555, 333.444.5555, 333-444-5555, 333 444 5555, (333) 444 5555 and all combinations thereof.
'\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}'</pre>
<p><span style="text-decoration: underline;">Postal codes</span></p>
<pre>//Postal code (Canada)
'\b[ABCEGHJKLMNPRSTVXY][0-9][A-Z] [0-9][A-Z][0-9]\b'

//Postal code (UK)
'\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b'</pre>
<p><span style="text-decoration: underline;">Programming</span></p>
<pre>//Programming: # comment
//Single-line comment started by # anywhere on the line
'#.*$'

//Programming: # preprocessor statement
//Started by # at the start of the line, possibly preceded by some whitespace.
'^\s*#.*$'

//Programming: /* comment */
//Does not match nested comments.  Most languages, including C, <a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">Java</a>, C#, etc.
//do not allow comments to be nested.  I.e. the first */ closes the comment.
'/\*.*?\*/'

//Programming: // comment
//Single-line comment started by // anywhere on the line
'//.*$'

//Programming: GUID
//Microsoft-style GUID, numbers only.
'[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}'

//Programming: GUID
//Microsoft-style GUID, with optional parentheses or braces.
//(Long version, if your <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> flavor doesn't support conditionals.)
'[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}|\([A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}\)|\{[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}\}'

//Programming: GUID
//Microsoft-style GUID, with optional parentheses or braces.
//Short version, illustrating the use of <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> conditionals.  Not all <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> flavors support conditionals.
//Also, when applied to large chunks of data, the <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> using conditionals will likely be slower
//than the long version.  Straight alternation is much easier to optimize for a <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> engine.
'(?:(\()|(\{))?[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}(?(1)\))(?(2)\})'

//Programming: Remove escapes
//Remove backslashes used to escape other characters
preg_replace('\\(.)', '\1', $text);

//Programming: String
//Quotes may appear in the string when escaped with a backslash.
//The string may span multiple lines.
'"[^"\\]*(?:\\.[^"\\]*)*"'

//Programming: String
//Quotes may appear in the string when escaped with a backslash.
//The string cannot span multiple lines.
'"[^"\\\r\n]*(?:\\.[^"\\\r\n]*)*"'

//Programming: String
//Quotes may not appear in the string.  The string cannot span multiple lines.
'"[^"\r\n]*"'</pre>
<p><span style="text-decoration: underline;">Quotes</span></p>
<pre>//Quotes: Replace smart double quotes with straight double quotes.
//ANSI version for use with 8-bit <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> engines and the Windows code page 1252.
preg_replace('[\x84\x93\x94]', '"', $text);

//Quotes: Replace smart double quotes with straight double quotes.
//Unicode version for use with Unicode <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> engines.
preg_replace('[\u201C\u201D\u201E\u201F\u2033\u2036]', '"', $text);

//Quotes: Replace smart single quotes and apostrophes with straight single quotes.
//Unicode version for use with Unicode <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> engines.
preg_replace("[\u2018\u2019\u201A\u201B\u2032\u2035]", "'", $text);

//Quotes: Replace smart single quotes and apostrophes with straight single quotes.
//ANSI version for use with 8-bit <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> engines and the Windows code page 1252.
preg_replace("[\x82\x91\x92]", "'", $text);

//Quotes: Replace straight apostrophes with smart apostrophes
preg_replace("\b'\b", "?", $text);

//Quotes: Replace straight double quotes with smart double quotes.
//ANSI version for use with 8-bit <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> engines and the Windows code page 1252.
preg_replace('\B"\b([^"\x84\x93\x94\r\n]+)\b"\B', '?\1?', $text);

//Quotes: Replace straight double quotes with smart double quotes.
//Unicode version for use with Unicode <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> engines.
preg_replace('\B"\b([^"\u201C\u201D\u201E\u201F\u2033\u2036\r\n]+)\b"\B', '?\1?', $text);

//Quotes: Replace straight single quotes with smart single quotes.
//Unicode version for use with Unicode <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> engines.
preg_replace("\B'\b([^'\u2018\u2019\u201A\u201B\u2032\u2035\r\n]+)\b'\B", "?\1?", $text);

//Quotes: Replace straight single quotes with smart single quotes.
//ANSI version for use with 8-bit <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> engines and the Windows code page 1252.
preg_replace("\B'\b([^'\x82\x91\x92\r\n]+)\b'\B", "?\1?", $text);</pre>
<p><span style="text-decoration: underline;">Escape</span></p>
<pre>//<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">Regex</a>: Escape metacharacters
//Place a backslash in front of the regular expression metacharacters
preg_replace("[][{}()*+?.\\^$|]", "\\$0", $text);</pre>
<p><span style="text-decoration: underline;">Security</span></p>
<pre>//Security: ASCII code characters excl. tab and CRLF
//Matches any single non-printable code character that may cause trouble in certain situations.
//Excludes tabs and line breaks.
'[\x00\x08\x0B\x0C\x0E-\x1F]'

//Security: ASCII code characters incl. tab and CRLF
//Matches any single non-printable code character that may cause trouble in certain situations.
//Includes tabs and line breaks.
'[\x00-\x1F]'

//Security: Escape quotes and backslashes
//E.g. escape user input before inserting it into a SQL statement
preg_replace("\\$0", "\\$0", $text);

//Security: Unicode code and unassigned characters excl. tab and CRLF
//Matches any single non-printable code character that may cause trouble in certain situations.
//Also matches any Unicode code point that is unused in the current Unicode standard,
//and thus should not occur in text as it cannot be displayed.
//Excludes tabs and line breaks.
'[^\P{C}\t\r\n]'

//Security: Unicode code and unassigned characters incl. tab and CRLF
//Matches any single non-printable code character that may cause trouble in certain situations.
//Also matches any Unicode code point that is unused in the current Unicode standard,
//and thus should not occur in text as it cannot be displayed.
//Includes tabs and line breaks.
'\p{C}'

//Security: Unicode code characters excl. tab and CRLF
//Matches any single non-printable code character that may cause trouble in certain situations.
//Excludes tabs and line breaks.
'[^\P{Cc}\t\r\n]'

//Security: Unicode code characters incl. tab and CRLF
//Matches any single non-printable code character that may cause trouble in certain situations.
//Includes tabs and line breaks.
'\p{Cc}'</pre>
<p><span style="text-decoration: underline;">SSN (Social security numbers)</span></p>
<pre>//Social security number (US)
'\b[0-9]{3}-[0-9]{2}-[0-9]{4}\b'</pre>
<p><span style="text-decoration: underline;">Trim</span></p>
<pre>//Trim whitespace (including line breaks) at the end of the string
preg_replace("\s+\z", "", $text);

//Trim whitespace (including line breaks) at the start and the end of the string
preg_replace("\A\s+|\s+\z", "", $text);

//Trim whitespace (including line breaks) at the start of the string
preg_replace("\A\s+", "", $text);

//Trim whitespace at the end of each line
preg_replace("[ \t]+$", "", $text);

//Trim whitespace at the start and the end of each line
preg_replace("^[ \t]+|[ \t]+$", "", $text);

//Trim whitespace at the start of each line
preg_replace("^[ \t]+", "", $text);</pre>
<p><span style="text-decoration: underline;">URL's</span></p>
<pre>//URL: Different URL parts
//Protocol, domain name, page and CGI parameters are captured into backreferenes 1 through 4
'\b((?#protocol)https?|ftp)://((?#domain)[-A-Z0-9.]+)((?#file)/[-A-Z0-9+&amp;@#/%=~_|!:,.;]*)?((?#parameters)\?[-A-Z0-9+&amp;@#/%=~_|!:,.;]*)?'

//URL: Different URL parts
//Protocol, domain name, page and CGI parameters are captured into named capturing groups.
//Works as it is with .NET, and after conversion by RegexBuddy on the Use page with Python, <a href="http://www.iwanna.cn/tags/php/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with PHP">PHP</a>/preg and PCRE.
'\b(?&lt;protocol&gt;https?|ftp)://(?&lt;domain&gt;[-A-Z0-9.]+)(?&lt;file&gt;/[-A-Z0-9+&amp;@#/%=~_|!:,.;]*)?(?&lt;parameters&gt;\?[-A-Z0-9+&amp;@#/%=~_|!:,.;]*)?'

//URL: Find in full text
//The final character class makes sure that if an URL is part of some text, punctuation such as a
//comma or full stop after the URL is not interpreted as part of the URL.
'\b(https?|ftp|file)://[-A-Z0-9+&amp;@#/%?=~_|!:,.;]*[-A-Z0-9+&amp;@#/%=~_|]'

//URL: Replace URLs with HTML links
preg_replace('\b(https?|ftp|file)://[-A-Z0-9+&amp;@#/%?=~_|!:,.;]*[-A-Z0-9+&amp;@#/%=~_|]', '&lt;a href="\0"&gt;\0&lt;/a&gt;', $text);</pre>
<p><span style="text-decoration: underline;">Words</span></p>
<pre>//Words: Any word NOT matching a particular <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a>
//This <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a> will match all words that cannot be matched by %<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">REGEX</a>%.
//Explanation: Observe that the negative lookahead and the \w+ are repeated together.
//This makes sure we test that %<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">REGEX</a>% fails at EVERY position in the word, and not just at any particular position.
'\b(?:(?!%<a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">REGEX</a>%)\w)+\b'

//Words: Delete repeated words
//Find any word that occurs twice or more in a row.
//Delete all occurrences except the first.
preg_replace('\b(\w+)(?:\s+\1\b)+', '\1', $text);

//Words: Near, any order
//Matches word1 and word2, or vice versa, separated by at least 1 and at most 3 words
'\b(?:word1(?:\W+\w+){1,3}\W+word2|word2(?:\W+\w+){1,3}\W+word1)\b'

//Words: Near, list
//Matches any pair of words out of the list word1, word2, word3, separated by at least 1 and at most 6 words
'\b(word1|word2|word3)(?:\W+\w+){1,6}\W+(word1|word2|word3)\b'

//Words: Near, ordered
//Matches word1 and word2, in that order, separated by at least 1 and at most 3 words
'\bword1(?:\W+\w+){1,3}\W+word2\b'

//Words: Repeated words
//Find any word that occurs twice or more in a row.
'\b(\w+)\s+\1\b'

//Words: Whole word
'\b%WORD%\b'

//Words: Whole word
//Match one of the words from the list
'\b(?:word1|word2|word3)\b'

//Words: Whole word at the end of a line
//Whitespace permitted after the word
'\b%WORD%\s*$'

//Words: Whole word at the end of a line
'\b%WORD%$'

//Words: Whole word at the start of a line
'^%WORD%\b'

//Words: Whole word at the start of a line
//Whitespace permitted before the word
'^\s*%WORD%\b'</pre>
<p><!--</p>
<div style="margin-top:10px;padding:5px;border:1px solid #ccc" mce_style="margin-top:10px;padding:5px;border:1px solid #ccc">
<div style="width:300px; float:left"><a href="http://www.phplogin.net" mce_href="http://www.phplogin.net" title="PHP login script" target="_blank" border="0"><img border="0" src="http://www.roscripts.com/uploads/banners/phplogin300.jpg" mce_src="http://www.roscripts.com/uploads/banners/phplogin300.jpg" alt="PHP login script"></a></div>
<div style="width:330px; float:right"><a href="http://www.wallpaperscript.net" mce_href="http://www.wallpaperscript.net" title="Wallpaper script" target="_blank" border="0"><img border="0" src="http://www.roscripts.com/uploads/banners/330_250.gif" mce_src="http://www.roscripts.com/uploads/banners/330_250.gif" alt="Wallpaper script"></a></div>
<div></div>
</div>
<p>--></pre>
<hr />
<p>© <a href="http://www.iwanna.cn">我想网</a> Akon 所有 , 2009. |
<a href="http://www.iwanna.cn/archives/2009/08/27/2195/">永久链接</a> |
<a href="http://www.iwanna.cn/archives/2009/08/27/2195/#comments">没有评论</a> |
提交到
<a rel="nofollow" target="_blank" href="http://www.google.com/reader/view/feed/http://www.iwanna.cn/archives/2009/08/27/2195/">Google Reader</a>
<a rel="nofollow" target="_blank" href="http://www.xianguo.com/subscribe.php?url=http://www.iwanna.cn/archives/2009/08/27/2195/">鲜果</a>
<a rel="nofollow" target="_blank" href="http://www.zhuaxia.com/add_channel.php?url=http://www.iwanna.cn/archives/2009/08/27/2195/">抓虾</a>
<hr />
</p>
	标签：<a href="http://www.iwanna.cn/topics/develope/php/" title="PHP" rel="tag nofollow">PHP</a>, <a href="http://www.iwanna.cn/tags/php/" title="PHP" rel="tag nofollow">PHP</a>, <a href="http://www.iwanna.cn/tags/regex/" title="RegEx" rel="tag nofollow">RegEx</a>, <a href="http://www.iwanna.cn/topics/develope/regex-develope/" title="RegEx" rel="tag nofollow">RegEx</a><br />

	<h2 class="related_post">您可能会感兴趣的其他文章</h2>
	<ul class="st-related-posts">
	<li><a href="http://www.iwanna.cn/archives/2009/07/05/1936/" title="PHP用正则表达式解析 XML (2009年07月5日)">PHP用正则表达式解析 XML</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/09/11/2233/" title="PHP中用正则表达式验证中文 (2009年09月11日)">PHP中用正则表达式验证中文</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/07/14/4566/" title="15个实用的PHP正则表达式 (2010年07月14日)">15个实用的PHP正则表达式</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/06/02/1652/" title="高级正则表达式的重要概念 (2009年06月2日)">高级正则表达式的重要概念</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/04/02/149/" title="设计模式之单例模式 (2009年04月2日)">设计模式之单例模式</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/07/31/2088/" title="论述PHP开发框架: What, When, Why and Which? (2009年07月31日)">论述PHP开发框架: What, When, Why and Which?</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/06/08/3767/" title="腾讯PHP程序员面试题目 (2010年06月8日)">腾讯PHP程序员面试题目</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/04/03/171/" title="简易Wordpress模板代码帮助手册中文版 (2009年04月3日)">简易Wordpress模板代码帮助手册中文版</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/06/08/3769/" title="用PHP数组对百万数据进行排重 (2010年06月8日)">用PHP数组对百万数据进行排重</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/07/05/1933/" title="用 PHP 读取和编写 XML DOM (2009年07月5日)">用 PHP 读取和编写 XML DOM</a> </li>
</ul>


<p><small>Feed enhanced by <a href='http://planetozh.com/blog/my-projects/wordpress-plugin-better-feed-rss/'>Better Feed</a> from  <a href='http://planetozh.com/blog/'>Ozh</a></small></p>
]]></content:encoded>
			<wfw:commentRss>http://www.iwanna.cn/archives/2009/08/27/2195/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>6个正则表达式工具</title>
		<link>http://www.iwanna.cn/archives/2009/08/16/2142/</link>
		<comments>http://www.iwanna.cn/archives/2009/08/16/2142/#comments</comments>
		<pubDate>Sat, 15 Aug 2009 17:03:56 +0000</pubDate>
		<dc:creator>seasun</dc:creator>
				<category><![CDATA[NetSoft]]></category>
		<category><![CDATA[RegEx]]></category>
		<category><![CDATA[Tool]]></category>

		<guid isPermaLink="false">http://www.iwanna.cn/?p=2142</guid>
		<description><![CDATA[正则表达式能够帮助用户和开发人员更加有效地查找和操纵文本内容。而且，正则表达式已经得到了许多脚本语言、编程语言和数据库的良好支持。就算你不是一个开发人员，而是一个垃圾站长，掌握正则表达式也能够让你事半功倍。
如果你不觉得正则表达式很难读写的话，要么你是一个天才，要么，你不是地球人。正则表达式的语法很令人头疼，即使对经常使用它的人来说也是如此。由于难于读写，容易出错，所以找一种工具对正则表达式进行测试是很有必要的。

正则表达式工具
正则表达式工具，拥有调试、查找、替换、分割功能，是学习和使用正则表达式对文本处理的优秀软件之一。Win32架构。不用安装其他支持环境。
RegEx Builder
正则表达式测试工具，占内存小。该软件要求您的电脑要装有.net framework（进入下载.net环境）才能正常使用。
BFC正则表达式开发测试工具
可用于正则表达式的书写和测试，没有什么技术含量，只是对正则表达式库的基本应用，可方便大家对表达式进行测试。
RegEx TestBed
一个.net的正则表达式测试工具。
Regex Tester
一个基于JS的在线正则表达式测试工具。
RegexBuddy
一个强大的正则表达式工具，包括对正则表达式的学习，测试，使用和保存等功能。但这是一个收费软件。
最后，推荐一个很不错的正则表达式入门教程 – 30分钟正则入门。

© 我想网 Akon 所有 , 2009. &#124;
永久链接 &#124;
没有评论 &#124;
提交到
Google Reader
鲜果
抓虾


	标签：NetSoft, RegEx, RegEx, Tool

	您可能会感兴趣的其他文章
	
	高级正则表达式的重要概念 
	美化你的Google阅读器 
	网页鼠标点击轨迹热图跟踪软件-ClickHeat 
	正则表达式入门 
	检查素数的正则表达式 
	替代微软Visio的免费开源软件：DIA 
	数据之美之50个数据图形化工具(下) 
	数据之美之50个数据图形化工具(上) 
	挑选VPS：Xen与OpenVZ有什么区别？ 
	微博通讯和即时通讯的对决 



Feed enhanced by Better Feed from  Ozh
]]></description>
			<content:encoded><![CDATA[<p>正则表达式能够帮助用户和开发人员更加有效地查找和操纵文本内容。而且，正则表达式已经得到了许多脚本语言、编程语言和数据库的良好支持。就算你不是一个开发人员，而是一个垃圾站长，掌握正则表达式也能够让你事半功倍。</p>
<p>如果你不觉得正则表达式很难读写的话，要么你是一个天才，要么，你不是地球人。正则表达式的语法很令人头疼，即使对经常使用它的人来说也是如此。由于难于读写，容易出错，所以找一种工具对正则表达式进行测试是很有必要的。<br />
<span id="more-2142"></span><br />
<a href="http://xdowns.com/soft/38/39/2009/Soft_53201.html">正则表达式工具</a></p>
<p>正则表达式工具，拥有调试、查找、替换、分割功能，是学习和使用正则表达式对文本处理的优秀软件之一。Win32架构。不用安装其他支持环境。</p>
<p><a href="http://www.redfernplace.com/software-projects/regex-builder/">RegEx Builder</a></p>
<p>正则表达式测试工具，占内存小。该软件要求您的电脑要装有.net framework（进入下载.net环境）才能正常使用。</p>
<p><a href="http://xdowns.com/soft/23/24/2008/Soft_44555.html">BFC正则表达式开发测试工具</a></p>
<p>可用于正则表达式的书写和测试，没有什么技术含量，只是对正则表达式库的基本应用，可方便大家对表达式进行测试。</p>
<p><a href="http://xdowns.com/soft/38/105/2008/Soft_44187.html">RegEx TestBed</a></p>
<p>一个.net的正则表达式测试工具。</p>
<p><a href="http://regexpal.com/">Regex Tester</a></p>
<p>一个基于JS的在线正则表达式测试工具。</p>
<p><a href="http://www.regexbuddy.com/">RegexBuddy</a></p>
<p>一个强大的正则表达式工具，包括对正则表达式的学习，测试，使用和保存等功能。但这是一个收费软件。</p>
<p>最后，推荐一个很不错的正则表达式入门教程 – <a href="http://unibetter.com/deerchao/zhengzhe-biaodashi-jiaocheng-se.htm" target="_blank">30分钟正则入门</a>。</p>
<hr />
<p>© <a href="http://www.iwanna.cn">我想网</a> Akon 所有 , 2009. |
<a href="http://www.iwanna.cn/archives/2009/08/16/2142/">永久链接</a> |
<a href="http://www.iwanna.cn/archives/2009/08/16/2142/#comments">没有评论</a> |
提交到
<a rel="nofollow" target="_blank" href="http://www.google.com/reader/view/feed/http://www.iwanna.cn/archives/2009/08/16/2142/">Google Reader</a>
<a rel="nofollow" target="_blank" href="http://www.xianguo.com/subscribe.php?url=http://www.iwanna.cn/archives/2009/08/16/2142/">鲜果</a>
<a rel="nofollow" target="_blank" href="http://www.zhuaxia.com/add_channel.php?url=http://www.iwanna.cn/archives/2009/08/16/2142/">抓虾</a>
<hr />
</p>
	标签：<a href="http://www.iwanna.cn/topics/software/net-soft/" title="NetSoft" rel="tag nofollow">NetSoft</a>, <a href="http://www.iwanna.cn/tags/regex/" title="RegEx" rel="tag nofollow">RegEx</a>, <a href="http://www.iwanna.cn/topics/develope/regex-develope/" title="RegEx" rel="tag nofollow">RegEx</a>, <a href="http://www.iwanna.cn/tags/tool/" title="Tool" rel="tag nofollow">Tool</a><br />

	<h2 class="related_post">您可能会感兴趣的其他文章</h2>
	<ul class="st-related-posts">
	<li><a href="http://www.iwanna.cn/archives/2009/06/02/1652/" title="高级正则表达式的重要概念 (2009年06月2日)">高级正则表达式的重要概念</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/07/19/4628/" title="美化你的Google阅读器 (2010年07月19日)">美化你的Google阅读器</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/07/01/1900/" title="网页鼠标点击轨迹热图跟踪软件-ClickHeat (2009年07月1日)">网页鼠标点击轨迹热图跟踪软件-ClickHeat</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/04/09/318/" title="正则表达式入门 (2009年04月9日)">正则表达式入门</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/07/23/4680/" title="检查素数的正则表达式 (2010年07月23日)">检查素数的正则表达式</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/10/09/2274/" title="替代微软Visio的免费开源软件：DIA (2009年10月9日)">替代微软Visio的免费开源软件：DIA</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/05/28/3530/" title="数据之美之50个数据图形化工具(下) (2010年05月28日)">数据之美之50个数据图形化工具(下)</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/05/28/3529/" title="数据之美之50个数据图形化工具(上) (2010年05月28日)">数据之美之50个数据图形化工具(上)</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/05/20/3244/" title="挑选VPS：Xen与OpenVZ有什么区别？ (2010年05月20日)">挑选VPS：Xen与OpenVZ有什么区别？</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/07/19/4620/" title="微博通讯和即时通讯的对决 (2010年07月19日)">微博通讯和即时通讯的对决</a> </li>
</ul>


<p><small>Feed enhanced by <a href='http://planetozh.com/blog/my-projects/wordpress-plugin-better-feed-rss/'>Better Feed</a> from  <a href='http://planetozh.com/blog/'>Ozh</a></small></p>
]]></content:encoded>
			<wfw:commentRss>http://www.iwanna.cn/archives/2009/08/16/2142/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP用正则表达式解析 XML</title>
		<link>http://www.iwanna.cn/archives/2009/07/05/1936/</link>
		<comments>http://www.iwanna.cn/archives/2009/07/05/1936/#comments</comments>
		<pubDate>Sun, 05 Jul 2009 15:06:17 +0000</pubDate>
		<dc:creator>seasun</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[RegEx]]></category>
		<category><![CDATA[XML]]></category>
		<category><![CDATA[Original]]></category>

		<guid isPermaLink="false">http://www.iwanna.cn/?p=1936</guid>
		<description><![CDATA[&#60;?php
$xml = &#8220;&#8221;;
$f = fopen( &#8216;books.xml&#8217;, &#8216;r&#8217; );
while( $data = fread( $f, 4096 ) ) { $xml .= $data; }
fclose( $f );
preg_match_all( &#8220;/\&#60;book\&#62;(.*?)\&#60;\/book\&#62;/s&#8221;, $xml, $bookblocks );
foreach( $bookblocks[1] as $block ) {
preg_match_all( &#8220;/\&#60;author\&#62;(.*?)\&#60;\/author\&#62;/&#8221;, $block, $author );
preg_match_all( &#8220;/\&#60;title\&#62;(.*?)\&#60;\/title\&#62;/&#8221;, $block, $title );
preg_match_all( &#8220;/\&#60;publisher\&#62;(.*?)\&#60;\/publisher\&#62;/&#8221;, $block, $publisher );
echo( $title[1][0] . &#8221; &#8211; &#8221; . $author[1][0] . &#8221; &#8211; &#8221; . [...]]]></description>
			<content:encoded><![CDATA[<p>&lt;?<a href="http://www.iwanna.cn/tags/php/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with PHP">php</a><br />
$<a href="http://www.iwanna.cn/tags/xml/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with XML">xml</a> = &#8220;&#8221;;<br />
$f = fopen( &#8216;books.<a href="http://www.iwanna.cn/tags/xml/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with XML">xml</a>&#8217;, &#8216;r&#8217; );<br />
while( $data = fread( $f, 4096 ) ) { $<a href="http://www.iwanna.cn/tags/xml/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with XML">xml</a> .= $data; }<br />
fclose( $f );</p>
<p>preg_match_all( &#8220;/\&lt;book\&gt;(.*?)\&lt;\/book\&gt;/s&#8221;, $<a href="http://www.iwanna.cn/tags/xml/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with XML">xml</a>, $bookblocks );</p>
<p>foreach( $bookblocks[1] as $block ) {<br />
preg_match_all( &#8220;/\&lt;author\&gt;(.*?)\&lt;\/author\&gt;/&#8221;, $block, $author );<br />
preg_match_all( &#8220;/\&lt;title\&gt;(.*?)\&lt;\/title\&gt;/&#8221;, $block, $title );<br />
preg_match_all( &#8220;/\&lt;publisher\&gt;(.*?)\&lt;\/publisher\&gt;/&#8221;, $block, $publisher );<br />
echo( $title[1][0] . &#8221; &#8211; &#8221; . $author[1][0] . &#8221; &#8211; &#8221; . $publisher[1][0] . &#8220;\n&#8221; );<br />
}<br />
?&gt;</p>
<p>正则表达式对于小量的<a href="http://www.iwanna.cn/tags/xml/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with XML">XML</a>数据解析比较高效，如果是大数据量的，那么就请使用 DOM 库读取 <a href="http://www.iwanna.cn/tags/xml/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with XML">XML</a> 或 SAX 解析器读取 <a href="http://www.iwanna.cn/tags/xml/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with XML">XML</a> 吧！！</p>
<hr />
<p>© <a href="http://www.iwanna.cn">我想网</a> Akon 所有 , 2009. |
<a href="http://www.iwanna.cn/archives/2009/07/05/1936/">永久链接</a> |
<a href="http://www.iwanna.cn/archives/2009/07/05/1936/#comments">没有评论</a> |
提交到
<a rel="nofollow" target="_blank" href="http://www.google.com/reader/view/feed/http://www.iwanna.cn/archives/2009/07/05/1936/">Google Reader</a>
<a rel="nofollow" target="_blank" href="http://www.xianguo.com/subscribe.php?url=http://www.iwanna.cn/archives/2009/07/05/1936/">鲜果</a>
<a rel="nofollow" target="_blank" href="http://www.zhuaxia.com/add_channel.php?url=http://www.iwanna.cn/archives/2009/07/05/1936/">抓虾</a>
<hr />
</p>
	标签：<a href="http://www.iwanna.cn/tags/original/" title="Original" rel="tag nofollow">Original</a>, <a href="http://www.iwanna.cn/topics/develope/php/" title="PHP" rel="tag nofollow">PHP</a>, <a href="http://www.iwanna.cn/tags/php/" title="PHP" rel="tag nofollow">PHP</a>, <a href="http://www.iwanna.cn/tags/regex/" title="RegEx" rel="tag nofollow">RegEx</a>, <a href="http://www.iwanna.cn/topics/develope/regex-develope/" title="RegEx" rel="tag nofollow">RegEx</a>, <a href="http://www.iwanna.cn/tags/xml/" title="XML" rel="tag nofollow">XML</a>, <a href="http://www.iwanna.cn/topics/develope/xml-develope/" title="XML" rel="tag nofollow">XML</a><br />

	<h2 class="related_post">您可能会感兴趣的其他文章</h2>
	<ul class="st-related-posts">
	<li><a href="http://www.iwanna.cn/archives/2009/07/05/1933/" title="用 PHP 读取和编写 XML DOM (2009年07月5日)">用 PHP 读取和编写 XML DOM</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/08/27/2195/" title="PHP正则表达式常用范例 (2009年08月27日)">PHP正则表达式常用范例</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/09/11/2233/" title="PHP中用正则表达式验证中文 (2009年09月11日)">PHP中用正则表达式验证中文</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/06/30/1894/" title="40+ Web前端开发必备的备忘单[上] (2009年06月30日)">40+ Web前端开发必备的备忘单[上]</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/07/14/4566/" title="15个实用的PHP正则表达式 (2010年07月14日)">15个实用的PHP正则表达式</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/06/02/1652/" title="高级正则表达式的重要概念 (2009年06月2日)">高级正则表达式的重要概念</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/04/07/226/" title="追忆阿桑 (2009年04月7日)">追忆阿桑</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/04/02/149/" title="设计模式之单例模式 (2009年04月2日)">设计模式之单例模式</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/07/31/2088/" title="论述PHP开发框架: What, When, Why and Which? (2009年07月31日)">论述PHP开发框架: What, When, Why and Which?</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/06/08/3767/" title="腾讯PHP程序员面试题目 (2010年06月8日)">腾讯PHP程序员面试题目</a> </li>
</ul>


<p><small>Feed enhanced by <a href='http://planetozh.com/blog/my-projects/wordpress-plugin-better-feed-rss/'>Better Feed</a> from  <a href='http://planetozh.com/blog/'>Ozh</a></small></p>
]]></content:encoded>
			<wfw:commentRss>http://www.iwanna.cn/archives/2009/07/05/1936/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>高级正则表达式的重要概念</title>
		<link>http://www.iwanna.cn/archives/2009/06/02/1652/</link>
		<comments>http://www.iwanna.cn/archives/2009/06/02/1652/#comments</comments>
		<pubDate>Tue, 02 Jun 2009 01:29:19 +0000</pubDate>
		<dc:creator>seasun</dc:creator>
				<category><![CDATA[RegEx]]></category>

		<guid isPermaLink="false">http://www.iwanna.cn/?p=1652</guid>
		<description><![CDATA[本文为您介绍正则表达式的高级技巧。我们筛选出了八个常用的概念，并配上实例解析，每个例子都是满足某种复杂要求的简单写法。如果你对正则的基本概念尚缺乏了解，请先阅读这篇文章，或者这个教程，或者维基条目。
这里的正则语法适用于PHP，与Perl兼容。]]></description>
			<content:encoded><![CDATA[<p><a class="bodytag" href="http://www.yeeyan.com/articles/tag/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F" target="_blank"><em>正则表达式</em></a>(Regular Expression,  <em>abbr. <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a></em>) 功能强大，能够用于在一大串字符里找到所需信息。它利用约定俗成的字符结构表达式来发生作用。不幸的是，简单的正则表达式对于一些高级运用，功能远远不够。若要进行筛选的结构比较复杂，你可能就需要用到<strong>高级<a class="bodytag" href="http://www.yeeyan.com/articles/tag/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F" target="_blank"><em>正则表达式</em></a></strong>。<br />
<span id="more-1652"></span><br />
本文为您<strong>介绍<a class="bodytag" href="http://www.yeeyan.com/articles/tag/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F" target="_blank"><em>正则表达式</em></a>的高级技巧</strong>。我们筛选出了八个常用的概念，并配上实例解析，每个例子都是满足某种复杂要求的简单写法。如果你对正则的基本概念尚缺乏了解，请先阅读<a title="正则表达式入门" href="http://unibetter.com/deerchao/zhengzhe-biaodashi-jiaocheng-se.htm#introduction" target="_blank">这篇文章</a>，或者<a href="http://www.regexlab.com/zh/deelx/syntax.htm" target="_blank">这个教程</a>，或者<a title="维基百科" href="http://zh.wikipedia.org/wiki/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F" target="_blank">维基条目</a>。</p>
<p>这里的正则语法适用于<a href="http://www.iwanna.cn/tags/php/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with PHP">PHP</a>，与<a title="维基百科" href="http://zh.wikipedia.org/wiki/Perl" target="_blank">Perl</a>兼容。</p>
<h3>1. 贪婪/懒惰</h3>
<p><img src="http://i27.photobucket.com/albums/c156/jyyjcc/benhuoer-blog/regular-expression/greed.jpg" alt="Greed" width="400" height="300" /></p>
<p>所有能多次限定的正则运算符都是贪婪的。他们<strong>尽可能多</strong>地匹配目标字符串，也就是说匹配结果会<strong>尽可能地长</strong>。不幸的是，这种做法并不总是我们想要的。因此，我们添加“懒惰”限定符来解决问题。在各个贪婪运算符后添加“?”能让表达式只匹配<strong>尽可能短</strong>的长度。另外，修改器“U”也能惰化能多次限定的运算符。理解贪婪与懒惰的区别是运用高级正则表达式的基础。</p>
<h4>贪婪操作符</h4>
<p>操作符 * 匹配之前的表达式零次或零次以上。它是一个贪婪操作符。请看下面的例子：</p>
<pre>preg_match( '/&lt;h1&gt;.*&lt;\/h1&gt;/', '&lt;h1&gt;这是一个标题。&lt;/h1&gt;

&lt;h1&gt;这是另一个。&lt;/h1&gt;', $matches );</pre>
<p>句点(.)能代表除换行符外的任意字符。上面的<a class="bodytag" href="http://www.yeeyan.com/articles/tag/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F" target="_blank"><em>正则表达式</em></a>匹配 h1 标签以及标签内的所有内容。它用句点(.)和星号(*)来匹配标签内的所有内容。匹配结果如下：</p>
<pre>&lt;h1&gt;这是一个标题。&lt;/h1&gt;&lt;h1&gt;这是另一个。&lt;/h1&gt;</pre>
<p>整个字串都被返回。* 操作符会连续匹配所有内容—— 甚至包括中间的 h1 闭合标签。因为它是贪婪的，匹配整个字串是符合其利益最大化原则。</p>
<h4>懒惰操作符</h4>
<p>把上面的式子稍作修改，加上一个问号(?)，能让表达式变懒惰：</p>
<pre>/&lt;h1&gt;.*?&lt;\/h1&gt;/</pre>
<p>这样它会觉得，只需匹配到第一个 h1 结尾标签就完成任务了。</p>
<p>另一个有着类似属性的贪婪操作符是 {n,} 。它代表之前的匹配模式重复n次或n次以上，如果没有加上问号，它会寻找尽可能多的重复次数，加上的话，则会尽可能少重复（当然也就是“重复n次”最少）。</p>
<pre># 建立字串
$str = 'hihihi oops hi';
# 使用贪婪的{n,}操作符进行匹配
preg_match( '/(hi){2,}/', $str, $matches );  # matches[0] 将是 'hihihi'
# 使用堕化了的 {n,}? 操作符匹配
preg_match( '/(hi){2,}?/', $str, $matches );  # matches[0] 将是 'hihi'</pre>
<h3>2. 回返引用(Back referencing)</h3>
<p><img src="http://i27.photobucket.com/albums/c156/jyyjcc/benhuoer-blog/regular-expression/back.jpg" alt="Back Referencing" width="300" height="290" /></p>
<h4>有什么用？</h4>
<p><strong>回返引用(Back referencing)</strong>一般被翻译成“反向引用”、“后向引用”、“向后引用”，个人觉得“回返引用”更为贴切[<a title="笨活儿" href="http://blog.benhuoer.com/">笨活儿</a>]。它是在正则表达式内部引用<strong>之前捕获到的内容</strong>的方法。例如，下面这个简单例子的目的是匹配出引号内部的内容：</p>
<pre># 建立匹配数组
$matches = array();

# 建立字串
$str = ""This is a 'string'"";

# 用<a class="bodytag" href="http://www.yeeyan.com/articles/tag/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F" target="_blank"><em>正则表达式</em></a>捕捉内容
preg_match( "/(\"|').*?(\"|')/", $str, $matches );

# 输出整个匹配字串
echo  $matches[0];</pre>
<p>它会输出：</p>
<pre>"This is a'</pre>
<p>显然，这并不是我们想要的内容。</p>
<p>这个表达式从开头的双引号开始匹配，遭遇单引号之后就错误地结束了匹配。这是因为表达式里说：(”|’)，也就是双引号(”)和单引号(’)均可。要修正这个问题，你可以用到回返引用。<strong>表达式\1,\2,…,\9</strong> 是对前面已捕获到的各个子内容的编组序号，能作为对这些编组的“指针”而被引用。在此例中，第一个被匹配的引号就由<code>\1</code>代表。</p>
<h4>如何运用？</h4>
<p>将上面的例子中，后面的闭合引号替换为1：</p>
<pre>preg_match( '/(\"|').*?\1/', $str, $matches );</pre>
<p>这会正确地返回字串：</p>
<pre>"This is a 'string'"</pre>
<blockquote><p><strong>译注思考题：</strong></p>
<p>如果是中文引号，前引号和后引号不是同一个字符，怎么办？</p></blockquote>
<p>还记得<a href="http://www.iwanna.cn/tags/php/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with PHP">PHP</a>函数 <code>preg_replace</code> 吗？其中也有回返引用。只不过我们没有用 \1 … \9，而是用了 $1 … $9 … $n （此处任意数目均可）作为回返指针。例如，如果你想把所有的段落标签<code>&lt;p&gt;</code>都替换成文本：</p>
<pre>$text = preg_replace( '/&lt;p&gt;(.*?)&lt;/p&gt;/',
"&amp;lt;p&amp;gt;$1&amp;lt;/p&amp;gt;", $html );</pre>
<p>参数$1是一个回返引用，代表段落标签<code>&lt;p&gt;</code>内部的文字，并插入到替换后的文本里。这种简便易用的表达式写法为我们提供了一个获取已匹配文字的简单方法，甚至在替换文本时也能使用。</p>
<h3>3. 已命名捕获组(Named Groups)</h3>
<p>当在一个表达式内多次用到回调引用时，很容易就把事情搞混淆，要弄清那些数字（1 … 9）都代表哪一个子内容是件很麻烦的事。回调引用的一个替代方法是使用带名字的捕获组（下文简称“有名组”）。有名组使用<code>(?P&lt;name&gt;pattern)</code>来设定，name代表组名，pattern是配合该有名组的正则结构。请看下面的例子：</p>
<pre>/(?P&lt;quote&gt;"|').*?(?P=quote)/</pre>
<p>上式中，quote就是组名，<code>"|'</code>是改组匹配内容的正则。后面的(?P=quote)是在调用组名为quote的有名组。这个式子的效果和上面的回调引用实例一样，只不过是用了有名组来实现。是不是更加易读易懂了？</p>
<p>有名组也能用于处理已匹配内容之数组的内部数据。赋予特定正则的组名也能作为所匹配到的内容在数组内部的索引词。</p>
<pre>preg_match( '/(?P&lt;quote&gt;"|\')/', "'String'", $matches );

# 下面的语句输出“'”(不包括双引号)
echo $matches[1];

# 使用组名调用，也会输出“'”
echo $matches['quote'];</pre>
<p>所以，有名组并不只是让写代码更容易，它也能用于组织代码。</p>
<h3>4. 字词边界(Word Boundaries)</h3>
<p><img src="http://i27.photobucket.com/albums/c156/jyyjcc/benhuoer-blog/regular-expression/boundary.jpg" alt="Word Boundaries" width="400" height="284" /></p>
<p><strong>字词边界</strong>是字串里的字词字符（包括字母、数字和下划线，自然也包括汉字）和非字词字符之间的位置。其特殊之处就在于，它并不匹配某个实在的字符。它的长度是<strong>零</strong>。 <code>\b</code> 匹配所有字词边界。</p>
<p>不幸的是，字词边界一般都被忽视掉了，大部分人都没有在意他的现实意义。 例如，如果你想要匹配单词“import”：</p>
<pre>/import/</pre>
<p>注意了！<a class="bodytag" href="http://www.yeeyan.com/articles/tag/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F" target="_blank"><em>正则表达式</em></a>有时候很调皮的。下面的字串也能和上面的式子匹配成功：</p>
<pre>important</pre>
<p>你或许觉得，只要在import前后加上空格，不就可以匹配这个独立的单词了：</p>
<pre>/ import /</pre>
<p>那如果遇上这种情况呢：</p>
<pre>The trader voted for the import</pre>
<p>当 import 这个词在字串开头或者结尾时，修改后的表达式仍然不能用。因此，考虑各种情况是必须的：</p>
<pre>/(^import | import | import$)/i</pre>
<p>别慌，还没完呢。如果遇到标点符号了呢？就为了满足这一个单词的匹配，你的正则可能就需要这样写：</p>
<pre>/(^import(:|;|,)? | import(:|;|,)? | import(\.|\?|\!)?$)/i</pre>
<p>对于只匹配一个单词来说，这样做实在是有点大动干戈了。正因如此，字词边界才显得意义重大。要适应上述要求，以及<strong>很多其他情况变种</strong>，有了字符边界，我们所需写的代码只是：</p>
<pre>/\bimport\b/</pre>
<p>上面所有情况都得到了解决。 <code>\b</code> 的灵活性就在于，它是一个没有长度的匹配。它只匹配两个实际字符之间想象出的位置。它检查两个相邻字符是否是一个为单字，另一个为非单字。情况符合，就返回匹配。如果遇到了单词的开头或结尾， <code>\b</code> 会把它当成是非单词字符对待。由于import里面的 <code>i</code> 仍然被看成是单词字符，import 就被匹配出来了。</p>
<p>注意，与<code>\b</code>相对，我们还有<code>\B</code>，此操作符匹配两个单字或者两个非单字之间的位置。因此，如果你想匹配在某个单词内部的‘hi’，可以使用：</p>
<pre>\Bhi\B</pre>
<p>“this”、“hight”，都会返回匹配，而“hi there”则不会返回匹配。</p>
<h3>5. 最小组团(Atomic Groups)</h3>
<p><img src="http://i27.photobucket.com/albums/c156/jyyjcc/benhuoer-blog/regular-expression/groups.jpg" alt="Advanced Operators" width="400" height="266" /></p>
<p><strong>最小组团</strong>是无捕捉的特殊正则表达式分组。通常用来提高正则表达式的效能，也能用于消除特定匹配。一个最小组团可以用(?&gt;pattern) 来定义，其中pattern是匹配式。</p>
<pre>/(?&gt;his|this)/</pre>
<p>当正则引擎针对最小组团进行匹配时，它会跳过组团内标记的回溯位置。以单词“smashing”为例，当用上面的<a class="bodytag" href="http://www.yeeyan.com/articles/tag/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F" target="_blank"><em>正则表达式</em></a>匹 配时，正则引擎会先尝试在“smashing”里寻找“his”。显然，找不到任何匹配。此时，最小组团就发挥作用了：正则引擎会放弃所有回溯位置。也就 是说，它不会尝试再从“smashing”里查找“this”。为什么要这样设置？因为“his”都没有返回匹配结果，包含有“his”的“this”当 然就更匹配不了了！</p>
<p>上面的例子并没有什么实用性，我们用<code>/t?his?/</code> 也能达到效果。再看看下面的例子：</p>
<pre>/\b(engineer|engrave|end)\b/</pre>
<p>如果把“engineering”拿去匹配，正则引擎会先匹配到“engineer”，但接下来就遇到了字词边界，b，所以匹配不成功。然后，正则 引擎又会尝试在字串里寻找下一个匹配内容：engrave。匹配到eng的时候，后面的又对不上了，匹配失败。最后，尝试“end”，结果同样是失败。仔 细观察，你会发现，一旦engineer匹配失败，并且都抵达了字词边界，“engrave”和“end”这两个词就已经不可能匹配成功了。这两个词都比 engineer短小，正则引擎不应该再多做无谓的尝试。</p>
<pre>/\b(?&gt;engineer|engrave|end)\b/</pre>
<p>上面的替代写法更能节省正则引擎的匹配时间，提高代码的工作效率。</p>
<h3>6. 递归(Recursion)</h3>
<p><img src="http://i27.photobucket.com/albums/c156/jyyjcc/benhuoer-blog/regular-expression/recursion.jpg" alt="Recursion" width="400" height="300" /></p>
<p><strong>递归(Recursion)</strong>用于匹配嵌套结构，例如括弧嵌套， (this (that))，HTML标签嵌套<code>&lt;div&gt;</code><code>&lt;div&gt;&lt;/div&gt;</code><code>&lt;/div&gt;</code>。我们使用<code>(?R)</code>来代表递归过程中的子模式。下面是一个匹配嵌套括弧的例子：</p>
<pre>/\(((?&gt;[^()]+)|(?R))*\)/</pre>
<p>最外层使用了反义符的括号“<code>\(</code>”匹配嵌套结构的开端。然后是一个多选项操作符<code>( * | * )</code>，可能匹配除括号外的所有字符 “<code>(?&gt;[^()]+)</code>”，也可能是通过子模式“<code>(?R)</code>”来再次匹配整个表达式。请注意，这个操作符会尽量多地匹配所有嵌套。</p>
<p>递归的另一个实例如下：</p>
<pre>/&lt;([\w]+).*?&gt;((?&gt;[^&lt;&gt;]+)|((?R)))*&lt;\/\1&gt;/</pre>
<p>以上表达式综合运用了字符分组，贪婪操作符、回溯，以及最小化组团来匹配嵌套标签。第一个括弧内分组<code>([w]+)</code>匹配出标签名，用于接下来的应用。若找到这尖括号样式的标签，则尝试寻找标签内容的剩余部分。下一个括弧括起来的子表达式和上一个实例非常相似：要么匹配不包括尖括号的所有字符 <code>?&gt;[^&lt;&gt;]+</code>，要么递归匹配整个表达式<code>(?R)</code>。表达式最后的<code>&lt;/1&gt;</code>代表闭合标签。</p>
<h3>7. 回调(Callbacks)</h3>
<p><img src="http://i27.photobucket.com/albums/c156/jyyjcc/benhuoer-blog/regular-expression/call.jpg" alt="Callbacks" width="400" height="290" /></p>
<p>匹配结果中的特定内容有时可能会需要某种特别的修改。要应用多重而复杂的修改，<a class="bodytag" href="http://www.yeeyan.com/articles/tag/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F" target="_blank"><em>正则表达式</em></a><strong>的回调</strong>就有了用武之地。回调是用于函数<code>preg_replace_callback</code>中的动态修改字串的方式。你可以为<code>preg_replace_callback</code>指定某个函数为参数，此函数能接收匹配结果数组为参数，并将数组修改后返回，作为替换的结果。</p>
<p>例如，我们想将某字串中的字母全部转变成大写。十分不巧，<a href="http://www.iwanna.cn/tags/php/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with PHP">PHP</a>没有直接转化字母大小写的正则操作符。要完成这项任务，就可以用到正则回调。首先，表达式要匹配出所有需要被大写的字母：</p>
<pre>/\b\w/</pre>
<p>上式同时使用了字词边界和字符类。光有这个式子还不够，我们还需要一个回调函数：</p>
<pre>function upper_case( $matches ) {
return strtoupper( $matches[0] );
}</pre>
<p>函数<code>upper_case</code>接收匹配结果数组，并将整个匹配结果转化成大写。 在此例中，<code>$matches[0]</code>代表需要被大写化的字母。然后，我们再利用<code>preg_replace_callback</code>实现回调：</p>
<pre>preg_replace_callback( '/\b\w/', "upper_case", $str );</pre>
<p>一个简单的回调即有这般强大的力量。</p>
<h3>8. 注释(Commenting)</h3>
<p><img src="http://i27.photobucket.com/albums/c156/jyyjcc/benhuoer-blog/regular-expression/comment.jpg" alt="Commenting" width="400" height="300" /></p>
<p><strong>注释</strong>不用来匹配字串，但确实是正则表达式中最重要的部分。当正则越写越深入，越写越复杂，要推译出究竟什么东西被匹配就会变得越来越困难。在正则表达式中间加上注释，是最小化将来的迷糊和困惑的最佳方式。</p>
<p>要在<a class="bodytag" href="http://www.yeeyan.com/articles/tag/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F" target="_blank"><em>正则表达式</em></a>内部加上注释，使用<code>(?#comment)</code>格式。把“comment”替换成你的注释语句：</p>
<pre>/(?#数字)\d/</pre>
<p>如果你打算把代码公之于众，为<a class="bodytag" href="http://www.yeeyan.com/articles/tag/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F" target="_blank"><em>正则表达式</em></a>加上注释就显得尤为重要。这样别人才能更容易看懂和修改你的代码。和其他场合的注释一样，这样做也能为你重访自己以前写的程序时提供方便。</p>
<p>考虑使用“x”或“(?x)”修改器来格式化注释。这个修改器让正则引擎忽略表达式参数之间的空格。“有用的”空格仍然能够通过<code>[ ]</code>或<code>\ </code>（反义符加空格）来匹配。</p>
<pre>/
\d    #digit
[ ]   #space
\w+   #word
/x</pre>
<p>上面的代码与下面的式子作用一样：</p>
<pre>/\d(?#digit)[ ](?#space)\w+(?#word)/</pre>
<p>请时刻注意代码的可读性。</p>
<h3>更多资源（英文）</h3>
<ul>
<li><a href="http://www.regular-expressions.info/" target="_blank">Regular-Expressions.info</a> Comprehensive website on regular expressions</li>
<li><a href="http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/" target="_blank"> Cheat Sheet</a>Informative regular expressions cheat sheet</li>
<li><a href="http://www.jslab.dk/tools.regex.php" target="_blank"> Regex Generator</a>JavaScript regular expressions generator</li>
</ul>
<h4>关于作者</h4>
<p><em>Karthik Viswanathan 是一个喜欢<a class="bodytag" href="http://www.yeeyan.com/articles/tag/%E7%BC%96%E7%A8%8B" target="_blank"><em>编程</em></a>和做网站的高中生。你可以到他的博客上查看他的作品：<a href="http://www.lateralcode.com/" target="_blank">Lateral Code</a>。你也可以关注一下他的线上<a href="http://twitter.lateralcode.com/" target="_blank">Twitter应用</a>。</em></p>
<hr />
<p>© <a href="http://www.iwanna.cn">我想网</a> Akon 所有 , 2009. |
<a href="http://www.iwanna.cn/archives/2009/06/02/1652/">永久链接</a> |
<a href="http://www.iwanna.cn/archives/2009/06/02/1652/#comments">没有评论</a> |
提交到
<a rel="nofollow" target="_blank" href="http://www.google.com/reader/view/feed/http://www.iwanna.cn/archives/2009/06/02/1652/">Google Reader</a>
<a rel="nofollow" target="_blank" href="http://www.xianguo.com/subscribe.php?url=http://www.iwanna.cn/archives/2009/06/02/1652/">鲜果</a>
<a rel="nofollow" target="_blank" href="http://www.zhuaxia.com/add_channel.php?url=http://www.iwanna.cn/archives/2009/06/02/1652/">抓虾</a>
<hr />
</p>
	标签：<a href="http://www.iwanna.cn/tags/regex/" title="RegEx" rel="tag nofollow">RegEx</a>, <a href="http://www.iwanna.cn/topics/develope/regex-develope/" title="RegEx" rel="tag nofollow">RegEx</a><br />

	<h2 class="related_post">您可能会感兴趣的其他文章</h2>
	<ul class="st-related-posts">
	<li><a href="http://www.iwanna.cn/archives/2009/04/09/318/" title="正则表达式入门 (2009年04月9日)">正则表达式入门</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/07/23/4680/" title="检查素数的正则表达式 (2010年07月23日)">检查素数的正则表达式</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/04/09/321/" title="常用的正则表达式 (2009年04月9日)">常用的正则表达式</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/07/05/1936/" title="PHP用正则表达式解析 XML (2009年07月5日)">PHP用正则表达式解析 XML</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/08/27/2195/" title="PHP正则表达式常用范例 (2009年08月27日)">PHP正则表达式常用范例</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/09/11/2233/" title="PHP中用正则表达式验证中文 (2009年09月11日)">PHP中用正则表达式验证中文</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/04/17/476/" title="Java过滤特殊字符的正则表达式 (2009年04月17日)">Java过滤特殊字符的正则表达式</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/08/16/2142/" title="6个正则表达式工具 (2009年08月16日)">6个正则表达式工具</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/07/14/4566/" title="15个实用的PHP正则表达式 (2010年07月14日)">15个实用的PHP正则表达式</a> </li>
</ul>


<p><small>Feed enhanced by <a href='http://planetozh.com/blog/my-projects/wordpress-plugin-better-feed-rss/'>Better Feed</a> from  <a href='http://planetozh.com/blog/'>Ozh</a></small></p>
]]></content:encoded>
			<wfw:commentRss>http://www.iwanna.cn/archives/2009/06/02/1652/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java过滤特殊字符的正则表达式</title>
		<link>http://www.iwanna.cn/archives/2009/04/17/476/</link>
		<comments>http://www.iwanna.cn/archives/2009/04/17/476/#comments</comments>
		<pubDate>Fri, 17 Apr 2009 02:01:59 +0000</pubDate>
		<dc:creator>seasun</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[RegEx]]></category>

		<guid isPermaLink="false">http://www.iwanna.cn/?p=476</guid>
		<description><![CDATA[Java正则表达式学习：
因为正则表达式是一个很庞杂的体系，此例仅举些入门的概念，更多的请参阅相关书籍及自行摸索。
\\ 反斜杠
\t 间隔 (&#8216;\u0009&#8242;)
\n 换行 (&#8216;\u000A&#8217;)
\r 回车 (&#8216;\u000D&#8217;)
\d 数字 等价于[0-9]
\D 非数字 等价于[^0-9]
\s 空白符号 [\t\n\x0B\f\r]
\S 非空白符号 [^\t\n\x0B\f\r]
\w 单独字符 [a-zA-Z_0-9]
\W 非单独字符 [^a-zA-Z_0-9]
\f 换页符
\e Escape
\b 一个单词的边界
\B 一个非单词的边界
\G 前一个匹配的结束
^为限制开头
^java     条件限制为以Java为开头字符
$为限制结尾
java$     条件限制为以java为结尾字符
. 条件限制除\n以外任意一个单独字符
java..     条件限制为java后除换行外任意两个字符
加入特定限制条件「[]」
[a-z]     条件限制在小写a to z范围中一个字符
[A-Z]     条件限制在大写A to Z范围中一个字符
[a-zA-Z] 条件限制在小写a to z或大写A to Z范围中一个字符
[0-9]     条件限制在小写0 to 9范围中一个字符
[0-9a-z] 条件限制在小写0 to 9或a to z范围中一个字符
[0-9[a-z]] 条件限制在小写0 to 9或a to z范围中一个字符(交集)
[]中加入^后加再次限制条件「[^]」
[^a-z]     条件限制在非小写a to [...]]]></description>
			<content:encoded><![CDATA[<p><strong><a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">Java</a>正则表达式学习：</strong><br />
因为正则表达式是一个很庞杂的体系，此例仅举些入门的概念，更多的请参阅相关书籍及自行摸索。</p>
<p>\\ 反斜杠<br />
\t 间隔 (&#8216;\u0009&#8242;)<br />
\n 换行 (&#8216;\u000A&#8217;)<br />
\r 回车 (&#8216;\u000D&#8217;)<br />
\d 数字 等价于[0-9]<br />
\D 非数字 等价于[^0-9]<br />
\s 空白符号 [\t\n\x0B\f\r]<br />
\S 非空白符号 [^\t\n\x0B\f\r]<br />
\w 单独字符 [a-zA-Z_0-9]<br />
\W 非单独字符 [^a-zA-Z_0-9]<br />
\f 换页符<br />
<span id="more-476"></span>\e Escape<br />
\b 一个单词的边界<br />
\B 一个非单词的边界<br />
\G 前一个匹配的结束</p>
<p>^为限制开头<br />
^<a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">java</a>     条件限制为以<a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">Java</a>为开头字符<br />
$为限制结尾<br />
<a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">java</a>$     条件限制为以<a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">java</a>为结尾字符<br />
. 条件限制除\n以外任意一个单独字符<br />
<a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">java</a>..     条件限制为<a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">java</a>后除换行外任意两个字符</p>
<p>加入特定限制条件「[]」<br />
[a-z]     条件限制在小写a to z范围中一个字符<br />
[A-Z]     条件限制在大写A to Z范围中一个字符<br />
[a-zA-Z] 条件限制在小写a to z或大写A to Z范围中一个字符<br />
[0-9]     条件限制在小写0 to 9范围中一个字符<br />
[0-9a-z] 条件限制在小写0 to 9或a to z范围中一个字符<br />
[0-9[a-z]] 条件限制在小写0 to 9或a to z范围中一个字符(交集)</p>
<p>[]中加入^后加再次限制条件「[^]」<br />
[^a-z]     条件限制在非小写a to z范围中一个字符<br />
[^A-Z]     条件限制在非大写A to Z范围中一个字符<br />
[^a-zA-Z] 条件限制在非小写a to z或大写A to Z范围中一个字符<br />
[^0-9]     条件限制在非小写0 to 9范围中一个字符<br />
[^0-9a-z] 条件限制在非小写0 to 9或a to z范围中一个字符<br />
[^0-9[a-z]] 条件限制在非小写0 to 9或a to z范围中一个字符(交集)</p>
<p>在限制条件为特定字符出现0次以上时，可以使用「*」<br />
J*     0个以上J<br />
.*     0个以上任意字符<br />
J.*D     J与D之间0个以上任意字符</p>
<p>在限制条件为特定字符出现1次以上时，可以使用「+」<br />
J+     1个以上J<br />
.+     1个以上任意字符<br />
J.+D     J与D之间1个以上任意字符</p>
<p>在限制条件为特定字符出现有0或1次以上时，可以使用「?」<br />
JA?     J或者JA出现</p>
<p>限制为连续出现指定次数字符「{a}」<br />
J{2}     JJ<br />
J{3}     JJJ<br />
文字a个以上，并且「{a,}」<br />
J{3,}     JJJ,JJJJ,JJJJJ,???(3次以上J并存)<br />
文字个以上，b个以下「{a,b}」<br />
J{3,5}     JJJ或JJJJ或JJJJJ<br />
两者取一「|」<br />
J|A     J或A<br />
<a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">Java</a>|Hello     <a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">Java</a>或Hello</p>
<p>「()」中规定一个组合类型<br />
比如，我查询&lt;a href=\&#8221;index.html\&#8221;&gt;index&lt;/a&gt;中&lt;a href&gt;&lt;/a&gt;间的数据，可写作&lt;a.*href=\&#8221;.*\&#8221;&gt;(.+?)&lt;/a&gt;</p>
<p>在使用Pattern.compile函数时，可以加入控制正则表达式的匹配行为的参数：<br />
Pattern Pattern.compile(String <a href="http://www.iwanna.cn/tags/regex/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with RegEx">regex</a>, int flag)</p>
<p>flag的取值范围如下：<br />
Pattern.CANON_EQ     当且仅当两个字符的&#8221;正规分解(canonical decomposition)&#8221;都完全相同的情况下，才认定匹配。比如用了这个标志之后，表达式&#8221;a\u030A&#8221;会匹配&#8221;?&#8221;。默认情况下，不考虑&#8221;规 范相等性(canonical equivalence)&#8221;。<br />
Pattern.CASE_INSENSITIVE(?i)     默认情况下，大小写不明感的匹配只适用于US-ASCII字符集。这个标志能让表达式忽略大小写进行匹配。要想对Unicode字符进行大小不明感的匹 配，只要将UNICODE_CASE与这个标志合起来就行了。<br />
Pattern.COMMENTS(?x)     在这种模式下，匹配时会忽略(正则表达式里的)空格字符(译者注：不是指表达式里的&#8221;\\s&#8221;，而是指表达式里的空格，tab，回车之类)。注释从#开始，一直到这行结束。可以通过嵌入式的标志来启用Unix行模式。<br />
Pattern.DOTALL(?s)     在这种模式下，表达式&#8217;.'可以匹配任意字符，包括表示一行的结束符。默认情况下，表达式&#8217;.'不匹配行的结束符。<br />
Pattern.MULTILINE<br />
(?m)     在这种模式下，&#8217;^'和&#8217;$'分别匹配一行的开始和结束。此外，&#8217;^'仍然匹配字符串的开始，&#8217;$'也匹配字符串的结束。默认情况下，这两个表达式仅仅匹配字符串的开始和结束。<br />
Pattern.UNICODE_CASE<br />
(?u)     在这个模式下，如果你还启用了CASE_INSENSITIVE标志，那么它会对Unicode字符进行大小写不明感的匹配。默认情况下，大小写不敏感的匹配只适用于US-ASCII字符集。<br />
Pattern.UNIX_LINES(?d)     在这个模式下，只有&#8217;\n&#8217;才被认作一行的中止，并且与&#8217;.'，&#8217;^'，以及&#8217;$'进行匹配。</p>
<p>抛开空泛的概念，下面写出几个简单的<a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">Java</a>正则用例：</p>
<p>◆比如，在字符串包含验证时</p>
<p>//查找以<a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">Java</a>开头,任意结尾的字符串<br />
Pattern pattern = Pattern.compile(&#8220;^<a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">Java</a>.*&#8221;);<br />
Matcher matcher = pattern.matcher(&#8220;<a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">Java</a>不是人&#8221;);<br />
boolean b= matcher.matches();<br />
//当条件满足时，将返回true，否则返回false<br />
System.out.println(b);</p>
<p>◆以多条件分割字符串时<br />
Pattern pattern = Pattern.compile(&#8220;[, |]+&#8221;);<br />
String[] strs = pattern.split(&#8220;<a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">Java</a> Hello World <a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">Java</a>,Hello,,World|Sun&#8221;);<br />
for (int i=0;i&lt;strs.length;i++) {<br />
System.out.println(strs[i]);<br />
}</p>
<p>◆文字替换（首次出现字符）<br />
Pattern pattern = Pattern.compile(&#8220;正则表达式&#8221;);<br />
Matcher matcher = pattern.matcher(&#8220;正则表达式 Hello World,正则表达式 Hello World&#8221;);<br />
//替换第一个符合正则的数据<br />
System.out.println(matcher.replaceFirst(&#8220;<a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">Java</a>&#8221;));</p>
<p>◆文字替换（全部）<br />
Pattern pattern = Pattern.compile(&#8220;正则表达式&#8221;);<br />
Matcher matcher = pattern.matcher(&#8220;正则表达式 Hello World,正则表达式 Hello World&#8221;);<br />
//替换第一个符合正则的数据<br />
System.out.println(matcher.replaceAll(&#8220;<a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">Java</a>&#8221;));</p>
<p>◆文字替换（置换字符）<br />
Pattern pattern = Pattern.compile(&#8220;正则表达式&#8221;);<br />
Matcher matcher = pattern.matcher(&#8220;正则表达式 Hello World,正则表达式 Hello World &#8220;);<br />
StringBuffer sbr = new StringBuffer();<br />
while (matcher.find()) {<br />
matcher.appendReplacement(sbr, &#8220;<a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">Java</a>&#8221;);<br />
}<br />
matcher.appendTail(sbr);<br />
System.out.println(sbr.toString());</p>
<p>◆验证是否为邮箱地址</p>
<p>String str=&#8221;ceponline@yahoo.com.cn&#8221;;<br />
Pattern pattern = Pattern.compile(&#8220;[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+&#8221;,Pattern.CASE_INSENSITIVE);<br />
Matcher matcher = pattern.matcher(str);<br />
System.out.println(matcher.matches());</p>
<p>◆去除html标记<br />
Pattern pattern = Pattern.compile(&#8220;&lt;.+?&gt;&#8221;, Pattern.DOTALL);<br />
Matcher matcher = pattern.matcher(&#8220;&lt;a href=\&#8221;index.html\&#8221;&gt;主页&lt;/a&gt;&#8221;);<br />
String string = matcher.replaceAll(&#8220;&#8221;);<br />
System.out.println(string);</p>
<p>◆查找html中对应条件字符串<br />
Pattern pattern = Pattern.compile(&#8220;href=\&#8221;(.+?)\&#8221;");<br />
Matcher matcher = pattern.matcher(&#8220;&lt;a href=\&#8221;index.html\&#8221;&gt;主页&lt;/a&gt;&#8221;);<br />
if(matcher.find())<br />
System.out.println(matcher.group(1));<br />
}</p>
<p>◆截取http://地址<br />
//截取url<br />
Pattern pattern = Pattern.compile(&#8220;(http://|https://){1}[\\w\\.\\-/:]+&#8221;);<br />
Matcher matcher = pattern.matcher(&#8220;dsdsds&lt;http://dsds//gfgffdfd&gt;fdf&#8221;);<br />
StringBuffer buffer = new StringBuffer();<br />
while(matcher.find()){<br />
buffer.append(matcher.group());<br />
buffer.append(&#8220;\r\n&#8221;);<br />
System.out.println(buffer.toString());<br />
}</p>
<p>◆替换指定{}中文字</p>
<p>String str = &#8220;<a href="http://www.iwanna.cn/tags/java/" class="st_tag internal_tag" rel="tag nofollow" title="Posts tagged with Java">Java</a>目前的发展史是由{0}年-{1}年&#8221;;<br />
String[][] object={new String[]{&#8220;\\{0\\}&#8221;,&#8221;1995&#8243;},new String[]{&#8220;\\{1\\}&#8221;,&#8221;2007&#8243;}};<br />
System.out.println(replace(str,object));</p>
<p>public static String replace(final String sourceString,Object[] object) {<br />
String temp=sourceString;<br />
for(int i=0;i&lt;object.length;i++){<br />
String[] result=(String[])object[i];<br />
Pattern    pattern = Pattern.compile(result[0]);<br />
Matcher matcher = pattern.matcher(temp);<br />
temp=matcher.replaceAll(result[1]);<br />
}<br />
return temp;<br />
}</p>
<p>◆以正则条件查询指定目录下文件</p>
<p>//用于缓存文件列表<br />
private ArrayList files = new ArrayList();<br />
//用于承载文件路径<br />
private String _path;<br />
//用于承载未合并的正则公式<br />
private String _regexp;</p>
<p>class MyFileFilter implements FileFilter {</p>
<p>/**<br />
* 匹配文件名称<br />
*/<br />
public boolean accept(File file) {<br />
try {<br />
Pattern pattern = Pattern.compile(_regexp);<br />
Matcher match = pattern.matcher(file.getName());<br />
return match.matches();<br />
} catch (Exception e) {<br />
return true;<br />
}<br />
}<br />
}</p>
<p>/**<br />
* 解析输入流<br />
* @param inputs<br />
*/<br />
FilesAnalyze (String path,String regexp){<br />
getFileName(path,regexp);<br />
}</p>
<p>/**<br />
* 分析文件名并加入files<br />
* @param input<br />
*/<br />
private void getFileName(String path,String regexp) {<br />
//目录<br />
_path=path;<br />
_regexp=regexp;<br />
File directory = new File(_path);<br />
File[] filesFile = directory.listFiles(new MyFileFilter());<br />
if (filesFile == null) return;<br />
for (int j = 0; j &lt; filesFile.length; j++) {<br />
files.add(filesFile[j]);<br />
}<br />
return;<br />
}</p>
<p>/**<br />
* 显示输出信息<br />
* @param out<br />
*/<br />
public void print (PrintStream out) {<br />
Iterator elements = files.iterator();<br />
while (elements.hasNext()) {<br />
File file=(File) elements.next();<br />
out.println(file.getPath());<br />
}<br />
}</p>
<p>public static void output(String path,String regexp) {</p>
<p>FilesAnalyze fileGroup1 = new FilesAnalyze(path,regexp);<br />
fileGroup1.print(System.out);<br />
}</p>
<p>public static void main (String[] args) {<br />
output(&#8220;C:\\&#8221;,&#8221;[A-z|.]*&#8221;);<br />
}</p>
<hr />
<p>© <a href="http://www.iwanna.cn">我想网</a> Akon 所有 , 2009. |
<a href="http://www.iwanna.cn/archives/2009/04/17/476/">永久链接</a> |
<a href="http://www.iwanna.cn/archives/2009/04/17/476/#comments">没有评论</a> |
提交到
<a rel="nofollow" target="_blank" href="http://www.google.com/reader/view/feed/http://www.iwanna.cn/archives/2009/04/17/476/">Google Reader</a>
<a rel="nofollow" target="_blank" href="http://www.xianguo.com/subscribe.php?url=http://www.iwanna.cn/archives/2009/04/17/476/">鲜果</a>
<a rel="nofollow" target="_blank" href="http://www.zhuaxia.com/add_channel.php?url=http://www.iwanna.cn/archives/2009/04/17/476/">抓虾</a>
<hr />
</p>
	标签：<a href="http://www.iwanna.cn/topics/develope/java/" title="Java" rel="tag nofollow">Java</a>, <a href="http://www.iwanna.cn/tags/java/" title="Java" rel="tag nofollow">Java</a>, <a href="http://www.iwanna.cn/tags/regex/" title="RegEx" rel="tag nofollow">RegEx</a>, <a href="http://www.iwanna.cn/topics/develope/regex-develope/" title="RegEx" rel="tag nofollow">RegEx</a><br />

	<h2 class="related_post">您可能会感兴趣的其他文章</h2>
	<ul class="st-related-posts">
	<li><a href="http://www.iwanna.cn/archives/2009/06/02/1652/" title="高级正则表达式的重要概念 (2009年06月2日)">高级正则表达式的重要概念</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/04/02/149/" title="设计模式之单例模式 (2009年04月2日)">设计模式之单例模式</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/04/09/318/" title="正则表达式入门 (2009年04月9日)">正则表达式入门</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/07/23/4680/" title="检查素数的正则表达式 (2010年07月23日)">检查素数的正则表达式</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/04/09/321/" title="常用的正则表达式 (2009年04月9日)">常用的正则表达式</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/07/05/1936/" title="PHP用正则表达式解析 XML (2009年07月5日)">PHP用正则表达式解析 XML</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/08/27/2195/" title="PHP正则表达式常用范例 (2009年08月27日)">PHP正则表达式常用范例</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/09/11/2233/" title="PHP中用正则表达式验证中文 (2009年09月11日)">PHP中用正则表达式验证中文</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/07/04/4353/" title="Java编程三十条规则 (2010年07月4日)">Java编程三十条规则</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/08/22/2183/" title="Java程序员十戒 (2009年08月22日)">Java程序员十戒</a> </li>
</ul>


<p><small>Feed enhanced by <a href='http://planetozh.com/blog/my-projects/wordpress-plugin-better-feed-rss/'>Better Feed</a> from  <a href='http://planetozh.com/blog/'>Ozh</a></small></p>
]]></content:encoded>
			<wfw:commentRss>http://www.iwanna.cn/archives/2009/04/17/476/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>常用的正则表达式</title>
		<link>http://www.iwanna.cn/archives/2009/04/09/321/</link>
		<comments>http://www.iwanna.cn/archives/2009/04/09/321/#comments</comments>
		<pubDate>Thu, 09 Apr 2009 04:19:32 +0000</pubDate>
		<dc:creator>seasun</dc:creator>
				<category><![CDATA[RegEx]]></category>

		<guid isPermaLink="false">http://www.iwanna.cn/?p=321</guid>
		<description><![CDATA[/^\[ \t]*$/ &#8220;^\[ \t]*$&#8221; 匹配一个空白行。
/\d{2}-\d{5}/ &#8220;\d{2}-\d{5}&#8221; 验证一个ID号码是否由一个2位字，一个连字符以及一个5位数字组成。
/&#60;(.*)&#62;.*&#60;\/\1&#62;/ &#8220;&#60;(.*)&#62;.*&#60;\/\1&#62;&#8221; 匹配一个 HTML 标记。
下表是元字符及其在正则表达式上下文中的行为的一个完整列表：

字符 描述
\ 将下一个字符标记为一个特殊字符、或一个原义字符、或一个 后向引用、或一个八进制转义符。例如，’n’ 匹配字符 &#8220;n&#8221;。’\n’匹配一个换行符。序列 ’\\’ 匹配 &#8220;\&#8221; 而 &#8220;\(&#8221; 则匹配 &#8220;(&#8220;。
^ 匹配输入字符串的开始位置。如果设置了 RegExp 对象的Multiline 属性，^ 也匹配 ’\n’ 或 ’\r’ 之后的位置。
$ 匹配输入字符串的结束位置。如果设置了 RegExp 对象的Multiline 属性，$ 也匹配 ’\n’ 或 ’\r’ 之前的位置。
* 匹配前面的子表达式零次或多次。例如，zo* 能匹配 &#8220;z&#8221; 以及&#8221;zoo&#8221;。 * 等价于{0,}。
+ 匹配前面的子表达式一次或多次。例如，’zo+’ 能匹配 &#8220;zo&#8221; 以及 &#8220;zoo&#8221;，但不能匹配 &#8220;z&#8221;。+ 等价于 {1,}。
? [...]]]></description>
			<content:encoded><![CDATA[<p>/^\[ \t]*$/ &#8220;^\[ \t]*$&#8221; 匹配一个空白行。</p>
<p>/\d{2}-\d{5}/ &#8220;\d{2}-\d{5}&#8221; 验证一个ID号码是否由一个2位字，一个连字符以及一个5位数字组成。</p>
<p>/&lt;(.*)&gt;.*&lt;\/\1&gt;/ &#8220;&lt;(.*)&gt;.*&lt;\/\1&gt;&#8221; 匹配一个 HTML 标记。<br />
下表是元字符及其在正则表达式上下文中的行为的一个完整列表：<br />
<span id="more-321"></span><br />
字符 描述</p>
<p>\ 将下一个字符标记为一个特殊字符、或一个原义字符、或一个 后向引用、或一个八进制转义符。例如，’n’ 匹配字符 &#8220;n&#8221;。’\n’匹配一个换行符。序列 ’\\’ 匹配 &#8220;\&#8221; 而 &#8220;\(&#8221; 则匹配 &#8220;(&#8220;。</p>
<p>^ 匹配输入字符串的开始位置。如果设置了 RegExp 对象的Multiline 属性，^ 也匹配 ’\n’ 或 ’\r’ 之后的位置。</p>
<p>$ 匹配输入字符串的结束位置。如果设置了 RegExp 对象的Multiline 属性，$ 也匹配 ’\n’ 或 ’\r’ 之前的位置。</p>
<p>* 匹配前面的子表达式零次或多次。例如，zo* 能匹配 &#8220;z&#8221; 以及&#8221;zoo&#8221;。 * 等价于{0,}。</p>
<p>+ 匹配前面的子表达式一次或多次。例如，’zo+’ 能匹配 &#8220;zo&#8221; 以及 &#8220;zoo&#8221;，但不能匹配 &#8220;z&#8221;。+ 等价于 {1,}。</p>
<p>? 匹配前面的子表达式零次或一次。例如，&#8221;do(es)?&#8221; 可以匹配&#8221;do&#8221; 或 &#8220;does&#8221; 中的&#8221;do&#8221; 。? 等价于 {0,1}。</p>
<p>{n} n 是一个非负整数。匹配确定的 n 次。例如，’o{2}’ 不能匹配&#8221;Bob&#8221; 中的 ’o’，但是能匹配 &#8220;food&#8221; 中的两个 o。</p>
<p>{n,} n 是一个非负整数。至少匹配n 次。例如，’o{2,}’ 不能匹配&#8221;Bob&#8221; 中的 ’o’，但能匹配 &#8220;foooood&#8221; 中的所有 o。’o{1,}’等价于 ’o+’。’o{0,}’ 则等价于 ’o*’。</p>
<p>{n,m} m 和 n 均为非负整数，其中n &lt;= m。最少匹配 n 次且最多匹配 m 次。刘， &#8220;o{1,3}&#8221; 将匹配 &#8220;fooooood&#8221; 中的前三个o。’o{0,1}’等价于’o?’。请注意在逗号和两个数之间不能有空格</p>
<p>? 当该字符紧跟在任何一个其他限制符 (*, +, ?, {n}, {n,}, {n,m}) 后面时，匹配模式是非贪婪的。非贪婪模式尽可能少的匹配所搜索的字符串，而默认的贪婪模式则尽可能多的匹配所搜索的字符串。例如，对于字符串 &#8220;oooo&#8221;，’o+?’ 将匹配单个&#8221;o&#8221;，而 ’o+’ 将匹配所有 ’o’。</p>
<p>. 匹配除 &#8220;\n&#8221; 之外的任何单个字符。要匹配包括 ’\n’ 在内的任<br />
何字符，请使用象 ’[.\n]’ 的模式。</p>
<p>(pattern) 匹配pattern 并获取这一匹配。所获取的匹配可以从产生的Matches 集合得到，在VBScript 中使用 SubMatches 集合，在Visual Basic Scripting Edition 中则使用 $0…$9 属性。要匹配圆括号字符，请使用 ’\(’ 或 ’\)’。</p>
<p>(?:pattern) 匹配 pattern 但不获取匹配结果，也就是说这是一个非获取匹配，不进行存储供以后使用。这在使用 &#8220;或&#8221; 字符 (|) 来组合一个模式的各个部分是很有用。例如， ’industr(?:y|ies) 就是一个比 ’industry|industries’ 更简略的表达式。</p>
<p>(?=pattern) 正向预查，在任何匹配 pattern 的字符串开始处匹配查找字符串。这是一个非获取匹配，也就是说，该匹配不需要获取供以后使用。例如，’Windows (?=95|98|NT|2000)’ 能匹配&#8221;Windows2000&#8243;中的&#8221;Windows&#8221;，但不能匹配&#8221;Windows3 .1&#8243;中&#8221;Windows&#8221;。<br />
预查不消耗字符，也就是说，在一个匹配发生后，在最后一次匹配之后立即开始下一次匹配的搜索，而不是从包含预查的字符之后开始。</p>
<p>(?!pattern) 负向预查，在任何不匹配Negative lookahead matches the search string at any point where a string not matching pattern 的字符串开始处匹配查找字符串。这是一个非获取匹配，也就是说，该匹配不需要获取供以后使用。例如’Windows (?!95|98|NT|2000)’ 能匹配 &#8220;Windows 3.1&#8243; 中的 &#8220;Windows&#8221;，但不能匹配 &#8220;Windows 2000&#8243; 中的 &#8220;Windows&#8221;。预查不消耗字符，也就是说，在一个匹配发生后，在最后一次匹配之后立即开始下一次匹配的搜索，而不是从包含预查的字符之后开始</p>
<p>x|y 匹配 x 或 y。例如，’z|food’ 能匹配 &#8220;z&#8221; 或 &#8220;food&#8221;。’(z|f) ood’ 则匹配 &#8220;zood&#8221; 或 &#8220;food&#8221;。</p>
<p>[xyz] 字符集合。匹配所包含的任意一个字符。例如， ’[abc]’ 可以匹配 &#8220;plain&#8221; 中的 ’a’。</p>
<p>[^xyz] 负值字符集合。匹配未包含的任意字符。例如， ’[^abc]’ 可以匹配 &#8220;plain&#8221; 中的’p’。</p>
<p>[a-z] 字符范围。匹配指定范围内的任意字符。例如，’[a-z]’ 可以匹配 ’a’ 到 ’z’ 范围内的任意小写字母字符。</p>
<p>[^a-z] 负值字符范围。匹配任何不在指定范围内的任意字符。例如，’[^a-z]’ 可以匹配任何不在 ’a’ 到 ’z’ 范围内的任意字符。</p>
<p>\b 匹配一个单词边界，也就是指单词和空格间的位置。例如，’er\b’ 可以匹配&#8221;never&#8221; 中的 ’er’，但不能匹配 &#8220;verb&#8221; 中的 ’er’。</p>
<p>\B 匹配非单词边界。’er\B’ 能匹配 &#8220;verb&#8221; 中的 ’er’，但不能匹配 &#8220;never&#8221; 中的 ’er’。</p>
<p>\cx 匹配由x指明的控制字符。例如， \cM 匹配一个 Control-M 或回车符。 x 的值必须为 A-Z 或 a-z 之一。否则，将 c 视为一个原义的 ’c’ 字符。</p>
<p>\d 匹配一个数字字符。等价于 [0-9]。</p>
<p>\D 匹配一个非数字字符。等价于 [^0-9]。</p>
<p>\f 匹配一个换页符。等价于 \x0c 和 \cL。</p>
<p>\n 匹配一个换行符。等价于 \x0a 和 \cJ。</p>
<p>\r 匹配一个回车符。等价于 \x0d 和 \cM。</p>
<p>\s 匹配任何空白字符，包括空格、制表符、换页符等等。等价于[ \f\n\r\t\v]。</p>
<p>\S 匹配任何非空白字符。等价于 [^ \f\n\r\t\v]。</p>
<p>\t 匹配一个制表符。等价于 \x09 和 \cI。</p>
<p>\v 匹配一个垂直制表符。等价于 \x0b 和 \cK。</p>
<p>\w 匹配包括下划线的任何单词字符。等价于’[A-Za-z0-9_]’。</p>
<p>\W 匹配任何非单词字符。等价于 ’[^A-Za-z0-9_]’。</p>
<p>\xn 匹配 n，其中 n 为十六进制转义值。十六进制转义值必须为确定的两个数字长。例如， ’\x41’ 匹配 &#8220;A&#8221;。’\x041’ 则等价于 ’\x04’ &amp; &#8220;1&#8243;。正则表达式中可以使用 ASCII 编码。.</p>
<p>\num 匹配 num，其中num是一个正整数。对所获取的匹配的引用。例如，’(.)\1’ 匹配两个连续的相同字符。</p>
<p>\n 标识一个八进制转义值或一个后向引用。如果 \n 之前至少 n 个获取的子表达式，则 n 为后向引用。否则，如果 n 为八进制数字 (0-7)，则 n 为一个八进制转义值。</p>
<p>\nm 标识一个八进制转义值或一个后向引用。如果 \nm 之前至少有is preceded by at least nm 个获取得子表达式，则 nm 为后向引用。如果 \nm 之前至少有 n 个获取，则 n 为一个后跟文<br />
字 m 的后向引用。如果前面的条件都不满足，若 n 和 m 均为八进制数字 (0-7)，则 \nm 将匹配八进制转义值 nm。</p>
<p>\nml 如果 n 为八进制数字 (0-3)，且 m 和 l 均为八进制数字 (0-7)，则匹配八进制转义值 nml。</p>
<p>\un 匹配 n，其中 n 是一个用四个十六进制数字表示的Unicode字符。例如， \u00A9 匹配版权符号 (?)。</p>
<hr />
<p>© <a href="http://www.iwanna.cn">我想网</a> Akon 所有 , 2009. |
<a href="http://www.iwanna.cn/archives/2009/04/09/321/">永久链接</a> |
<a href="http://www.iwanna.cn/archives/2009/04/09/321/#comments">没有评论</a> |
提交到
<a rel="nofollow" target="_blank" href="http://www.google.com/reader/view/feed/http://www.iwanna.cn/archives/2009/04/09/321/">Google Reader</a>
<a rel="nofollow" target="_blank" href="http://www.xianguo.com/subscribe.php?url=http://www.iwanna.cn/archives/2009/04/09/321/">鲜果</a>
<a rel="nofollow" target="_blank" href="http://www.zhuaxia.com/add_channel.php?url=http://www.iwanna.cn/archives/2009/04/09/321/">抓虾</a>
<hr />
</p>
	标签：<a href="http://www.iwanna.cn/tags/regex/" title="RegEx" rel="tag nofollow">RegEx</a>, <a href="http://www.iwanna.cn/topics/develope/regex-develope/" title="RegEx" rel="tag nofollow">RegEx</a><br />

	<h2 class="related_post">您可能会感兴趣的其他文章</h2>
	<ul class="st-related-posts">
	<li><a href="http://www.iwanna.cn/archives/2009/06/02/1652/" title="高级正则表达式的重要概念 (2009年06月2日)">高级正则表达式的重要概念</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/04/09/318/" title="正则表达式入门 (2009年04月9日)">正则表达式入门</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/07/23/4680/" title="检查素数的正则表达式 (2010年07月23日)">检查素数的正则表达式</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/07/05/1936/" title="PHP用正则表达式解析 XML (2009年07月5日)">PHP用正则表达式解析 XML</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/08/27/2195/" title="PHP正则表达式常用范例 (2009年08月27日)">PHP正则表达式常用范例</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/09/11/2233/" title="PHP中用正则表达式验证中文 (2009年09月11日)">PHP中用正则表达式验证中文</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/04/17/476/" title="Java过滤特殊字符的正则表达式 (2009年04月17日)">Java过滤特殊字符的正则表达式</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2009/08/16/2142/" title="6个正则表达式工具 (2009年08月16日)">6个正则表达式工具</a> </li>
	<li><a href="http://www.iwanna.cn/archives/2010/07/14/4566/" title="15个实用的PHP正则表达式 (2010年07月14日)">15个实用的PHP正则表达式</a> </li>
</ul>


<p><small>Feed enhanced by <a href='http://planetozh.com/blog/my-projects/wordpress-plugin-better-feed-rss/'>Better Feed</a> from  <a href='http://planetozh.com/blog/'>Ozh</a></small></p>
]]></content:encoded>
			<wfw:commentRss>http://www.iwanna.cn/archives/2009/04/09/321/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
