티스토리 뷰

웹개발/Javascript

Javascript RegEx Api

yaku 2010. 12. 14. 10:54
* Javascript RegEx Api The RegExp object RegExp 글로벌 오브젝트는 3가지 사용을 제시한다.
var a = new RegExp("\\b[\\w]{4}\\b","g"); //match all four letter words

//same as...
a = /\b\w{4}\b/g;
a.constructor //RegExp()

"(penalty)Lampard, Frank(1-0)".match(/\b([\w]+),\s?([\w]+)/g);

RegExp.leftContext //"(penalty)"
RegExp.rightContext //"(1-0)"
RegExp.$1 //"Lampard"
RegExp.$2 //"Frank"

var a = /\b[a-z]{10,}\b/i; //match long alpha-only word

RegExp.input=document.body.innerHTML;

a.test(); //true (on google.com)

var expr = /\b([^@\(]+)\(?(\d*)\)?@([^\s]+)\s?/g
var theString = '3@Clubs King(10)@Hearts 3@Spades 5@Diamonds 7@Clubs 2@Hearts 9@Spades Jack(10)@Clubs 4@Diamonds 9@Hearts';
var result = [], total=0, matching = true;

while(true) {
    var matching = expr.exec(theString);
    var value = parseInt(RegExp.$2 ? RegExp.$2 : RegExp.$1);
    if (!matching || (total += value)>21) {
        break;
    }
    alert('&' + RegExp.$1);
    result.push(RegExp.$1 + " of " + RegExp.$3);
}

alert(result); //["3 of Clubs", "King of Hearts", "3 of Spades", "5 of Diamonds"]

var a = /(-[\d*\.\d*]{2,})|(-\d+)/g //all negative numbers

"74 -5.6 9 -.5 -2 49".match(a); //["-5.6", "-.5", "-2"]
RegExp.$2; //"-2"
RegExp.leftContext; //"74 -5.6 9 -.5 "

var queryExpr = new RegExp(/\?/);
var getQueryString = function(url) {
    url.match(queryExpr);
    return RegExp.rightContext;
}
var g = getQueryString("http://www.wunderground.com/cgi-bin/findweather/getForecast?query=94101&hourly=1&yday=138&weekday=Wednesday");
//"?query=94101&hourly=1&yday=138&weekday=Wednesday";

var names = "Smith%20O'Shea%20Cameron%44Brown".split(/[^a-z\']+/gi); //names = ["Smith", "O'Shea", "Cameron", "Brown"];
RegExp.lastMatch; //"%44"

var time = "Two o'clock PM".split(/(o'clock)/);
//time = ['Two','PM'] (IE)
//time = ['Two', 'o,clock', 'PM'] (FF, webkit)

var a = "Smith, Bob; Raman, Ravi; Jones, Mary";
a.replace(/([\w]+), ([\w]+)/g,"$2 $1"); //"Bob Smith; Ravi Raman; Mary Jones"

var a  = "California, San Francisco, O'Rourke, Gerry";
a.replace(/([\w'\s]+), ([\w'\s]+), ([\w'\s]+), ([\w'\s]+)/,"$4 $3 lives in $2, $1"); //"Gerry O'Rourke lives in San Francisco, California"

var chars = "72 101 108 108 111  87 111 114 108 100 33";
chars.replace(/(\d+)(\s?)/gi,function(all,$1){return String.fromCharCode($1)}); //"Hello World!"
댓글
D-DAY
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함