《Regular Expression Cookbook》学习笔记——单词、文本行和特殊字符

来源:互联网 发布:淘宝售后差评回复 编辑:程序博客网 时间:2024/05/20 02:21
  • 查找一个特定单词(全部匹配,不区分大小写): \bword\b
正则选项:不区分大小写
正则流派:.net、Java、JavaScript、PCRE、Perl、Python、Ruby
讨论:单词边界使得word严格匹配(以整个单词形式出现,字母、数字、下划线也属于单词字符)。在正则表达式流派中,只有位于ASCII字符表的字母才能创建单词边界。

  • 查找多个单词之一(单词匹配):\b(?:one|two|three)\b
正则选项:不区分大小写
正则流派:.net、Java、JavaScript、PCRE、Perl、Python、Ruby
讨论:JavaScript示例
var subject = "One times two plus one equals three.";var regex = /\b(?:one|two|three)\b/gi;subject.match(regex);//返回数组:['One','two','one','three']//This function does the same thing but accepts an array of words to match.//Any regex matacharacters within the accepted words //are escaped witn a backslash before searching.function match_words (subject, words) {    var regex_metachars = /[(){}[\]*+?.\\^$|,\-]/g;    for (var i = 0; i < words.length; i++){        words[i] = words[i].replace(regex_metachars, '\\{1}');    }    var regex = new RegExp('\\b(?:' + words.join('|') + ')\\b', 'gi');    return subject.match(regex) || [];}match_words(subject, ['one' , 'two', 'three']);//返回数组:['One','two','one','three']
使用在多选结构,若没有单词边界,应该把长单词放在前边,否则有可能无法得到想要的结果(比如<aw|awesome>永远不会得到awesome。
第一种方法找不到匹配时返回null。
第二种方法先对所给的单词中可能出现的任何正则表达式元字符进行转义,然后把单词列表组成一个新的正则表达式,用其对字符串进行搜索。无匹配时返回空字符串。

  • 查找除单个单词之外的任意单词\b(?!word\b)\w+
正则选项:不区分大小写
正则流派:.net、Java、JavaScript、PCRE、Perl、Python、Ruby
讨论:变体查找不包含另一个单词的单词\b(?:(?!word)\w)+\b
正则选项:不区分大小写
正则流派:.net、Java、JavaScript、PCRE、Perl、Python、Ruby
与上一个表达式不同的是,这个正则表达式要求使用一个中止的单词边界。否则他只会匹配到一个单词的前面一部分,知道出现word的位置为止。

  • 查找后边不跟着某个特定单词的任意单词\b\w+\b(?!W+word\b)
正则选项:不区分大小写
正则流派:.net、Java、JavaScript、PCRE、Perl、Python、Ruby
讨论:关键在于否定型顺序环视。变体查找后边跟着某个特定单词的任意单词\b\w+\b(?=W+word\b)

  • 查找不跟在某个特定单词后边的任意单词(采用或模拟逆序环视)
  1. (?<!\bword\W+)\b\w+                            正则流派:.net
  2. (?<!\bword\W{1,9})\b\w+                       正则流派:.net、Java、PCRE
  3. (?<!\bword)(?:\W+|^)(\w+)                    正则流派:.net、Java、PCRE、Perl、Python、Ruby 1.9
  4. 模拟逆序环视(Javascript示例):
    var subject = 'My cat is Furry',      main_regex = /\b\w+/g,      lookbehind = /\bcat\W+$/i,      lookbehind_type = false, //negative lookbehind      matches = [],      match,      left_context;while (match = main_regex.exec(subject)) {      left_context = subject.substring(0, match.index);      if (lookbehind_type == lookbehind.test(left_context)){          matches.push(match[0]);      } else{          main_regex.lastIndex = match.index + 1;      }}//matches: ['My','cat','Furry']

  • 查找重复单词\b([A-Z]+)\s+\l\b
正则选项:不区分大小写
正则流派:.net、Java、JavaScript、PCRE、Perl、Python、Ruby

  • 对正则表达式进行转义
正则选项:不区分大小写
正则流派:.net、Java、JavaScript、PCRE、Perl、Python、Ruby
讨论:
最好使用内置的解决方案:
语言函数C#、VB.NETRegex.Escape(str)JavaPattern.quote(str)Perlquotemeta(str)PHPpreg_quote(str,[delimiter])Pythonre.escape(str)RubyRegexp.escape(str)










表1 对正则表达式元字符进行转义的内置解决方案

替代:
  1. \$&                替代文本流派:.NET、Javascript
  2. \\$&               替代文本流派:Perl
  3. \\$0               替代文本流派:Java、PHP
  4. \\\0                替代文本流派:PHP、Ruby
  5. \\\&                替代文本流派:Ruby
  6. \\\g<0>         替代文本流派:Python
Javascript函数示例:
RegExp.escape = function(){return str.replace(/ [[\]{}()*+?.\\|^$\-,&#\s]/g, "\\{1}");};//Test it out...var str = "Hello.World?";var escape_str = RegExp.escape(str);alert(escape_str == "Hello\\.World\\?"); //  -> true


原创粉丝点击