美文网首页
正则表达式

正则表达式

作者: stone_yao | 来源:发表于2016-05-05 20:00 被阅读145次

    参考:
    正则总结:JavaScript中的正则表达式
    Regular Expressions---<small>可以切换成中文模式</small>

    Regular Expressions

    <br />

    Regular expressions are patterns used to match character combinations in strings.

    Creating a regular expression

    You construct a regular expression in one of two ways:

    1.Using a regular expression literal, which consists of a pattern enclosed between slashes, as follows:

    var re = /ab+c/;
    

    2.calling the constructor function of the RegExp object, as follows:

    var re = new RegExp("ab+c");
    
    Example
    //get url params
    function getURLParameter(name) {
      return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
    }
    //[?|&]    ---以?或者|或者&开头
    //([^&;]+?)---非&或非;的字符,进行惰性匹配。
    //(&|#|;|$)---&或者#或者;或者文件尾
    
    

    ('x') Matches 'x' and remembers the match, as the following example shows. The parentheses are called capturing parentheses.
    The '(foo)' and '(bar)' in the pattern /(foo) (bar) \1 \2/ match and remember the first two words in the string "foo bar foo bar". The \1 and \2 in the pattern match the string's last two words. Note that \1, \2, \n are used in the matching part of the regex. In the replacement part of a regex the syntax $1, $2, $n must be used, e.g.: 'bar foo'.replace( /(...) (...)/, '$2 $1' ).

    //make reference to http://stackoverflow.com/questions/17779744/regular-expression-to-get-a-string-between-parentheses-in-javascript
    //Regular Expression to get a string between parentheses in Javascript
    var regExp = /\(([^)]+)\)/;
    var matches = regExp.exec("I expect five hundred dollars ($500).");
    
    //matches[1] contains the value between the parentheses
    console.log(matches[1]);
    
    
    //get url params
    function GetQueryString(name) {
               var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
               var r = window.location.search.substr(1).match(reg);
               if(r!=null)return  escape(r[2]); return null;
           }
    

    相关文章

      网友评论

          本文标题:正则表达式

          本文链接:https://www.haomeiwen.com/subject/ddwdrttx.html