MonkeyHua

正则表达式七:位置匹配

介绍

用来匹配字母、字符边界位置

元字符列表

  • 单词首末位置匹配:\b
  • 字符串开始位置匹配:^
  • 字符串结束位置匹配:$
  • 启用多行匹配部分支持(?m)

单词位置匹配(\b

匹配单词开始或者结束位置

示例

原始内容:

The captain wore his cap and cape proudly as
he sat listening to the recap of how his
crew saved the men from a capsized vessel.

正则表达式1:

\bcap

The captain wore his cap and cape proudly as
he sat listening to the recap of how his
crew saved the men from a capsized vessel.

说明:\bcap代表匹配以字符cap开头的单词

正则表达式2:

cat\b

The captain wore his cap and cape proudly as
he sat listening to the recap of how his
crew saved the men from a capsized vessel.

说明:cap\b代表匹配以字符cap结尾的单词

正则表达式3:

\bcat\b

The captain wore his cap and cape proudly as
he sat listening to the recap of how his
crew saved the men from a capsized vessel.

说明:\bcap\b代表匹配单词cap

字符串位置匹配(^$

匹配字符串开始或结束位置

示例

原始内容:

<?xml version="1.0" encoding="UTF-8" ?>
<wsdl:definitions targetNamespace="http://tips.cf"
xmlns:impl="http://tips.cf" xmlns:intf="http://tips.cf"
xmlns:apachesoap="http://xml.apache.org/xml-soap"

正则表达式:

^\s*<\?xml.*\?>

<?xml version="1.0" encoding="UTF-8" ?>
<wsdl:definitions targetNamespace="http://tips.cf"
xmlns:impl="http://tips.cf" xmlns:intf="http://tips.cf"
xmlns:apachesoap="http://xml.apache.org/xml-soap"

说明:^\s*代表字符串以一个或多个空白字符开头

多行匹配部分支持(?m)

需置于表达式开始处,代表支持匹配多行,通过强迫正则表达式引擎将换行符视作字符串分隔符来实现

示例

原始内容:

function doSpellCheck(form, field) {
// Make sure not empty
if (field.value == '') {
return false;
}
// Init
var windowName='spellWindow';
var spellCheckURL='spell.cfm?formname=comment&fieldname='+field.name;
∙∙∙
// Done
return false;
}

正则表达式1:

^\s*\/\/.*$

function doSpellCheck(form, field) {
// Make sure not empty
if (field.value == '') {
return false;
}
// Init
var windowName='spellWindow';
var spellCheckURL='spell.cfm?formname=comment&fieldname='+field.name;
∙∙∙
// Done
return false;
}

说明:当前没有内容匹配上,有且只存在一行注释内容时,才会匹配上

正则表达式2:

(?m)^\s*\/\/.*$

function doSpellCheck(form, field) {
// Make sure not empty
if (field.value == '') {
return false;
}
// Init
var windowName='spellWindow';
var spellCheckURL='spell.cfm?formname=comment&fieldname='+field.name;
∙∙∙
// Done
return false;
}

说明:(?m)代表启用多行匹配
\/\/代表匹配注释符号
.*代表匹配任意注释内容
^$代表匹配字符串起始、结束位置

posted on 2026-03-25 14:59  MonkeyHua  阅读(1)  评论(0)    收藏  举报

导航