当前位置: 代码迷 >> JavaScript >> JavaScript正则表达式:婚配位置
  详细解决方案

JavaScript正则表达式:婚配位置

热度:1472   发布时间:2013-02-26 00:00:00.0
JavaScript正则表达式:匹配位置

在JavaScript正则表达式中,匹配开头、结尾、单词开始、单词结尾等有特殊的表示方法,列举如下:

匹配位置语法描述
n$匹配任何结尾为 n 的字符串。
^n匹配任何开头为 n 的字符串。
?=n匹配任何其后紧接指定字符串 n 的字符串。
?!n匹配任何其后没有紧接指定字符串 n 的字符串。
\b查找位于单词的开头或结尾的匹配。
\B查找不处在单词的开头或结尾的匹配。

?

示例1:对字符串结尾的 "is" 进行全局搜索。

var str="Is this his";var patt1=/is$/g;document.write(str.match(patt1));

执行结果:

is

示例2:对字符串开头的 "is" 进行全局搜索。

var str="Is this his";var patt1=/^Is/g;document.write(str.match(patt1));

执行结果:

Is

示例3:对其后紧跟 "all" 的 "is" 进行全局搜索。

var str="Is this all there is";var patt1=/is(?= all)/;document.write(str.match(patt1));

执行结果:

is

示例4:对其后没有紧跟 "all" 的 "is" 进行全局搜索。

var str="Is this all there is";var patt1=/is(?! all)/gi;document.write(str.match(patt1));

执行结果:

Is,is

示例5:对字符串中的单词的开头或结尾进行 "W3" 的全局搜索。

var str="Visit W3School"; var patt1=/\bW3/g;document.write(str.match(patt1));

执行结果:

W3

示例6:对字符串中不位于单词开头或结尾的 "School" 进行全局搜索。

var str="Visit W3School"; var patt1=/\BSchool/g;document.write(str.match(patt1));

执行结果:

School

?

  • 源文【JavaScript正则表达式:匹配位置】最新版,请访问:
    ???http://www.vktone.com/articles/js-regexp-position
  • 更多关于【正则表达式】的文章,请访问:
    ???http://www.vktone.com/tags/regexp

?