Skip to content

Instantly share code, notes, and snippets.

@ishiduca
Created November 10, 2012 12:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ishiduca/4050905 to your computer and use it in GitHub Desktop.
Save ishiduca/4050905 to your computer and use it in GitHub Desktop.
RegExpのクローンを試す
function cloneRegExp (reg) {
if (! (reg instanceof RegExp)) throw new Error('TypeError: "reg" is not "RegExp"');
var _source = reg.source;
var _string = reg.toString();
var pos = _string.lastIndexOf('/');
return new RegExp(_source, _string.slice(pos+1));
}
module.exports.cloneRegExp = cloneRegExp;
var u = require('cloneRegExp');
var reg1 = /abd/;
var reg1c = u.cloneRegExp(reg1);
console.log(reg1);
console.log(reg1c);
var reg2 = /abd/ig;
var reg2c = u.cloneRegExp(reg2);
console.log(reg2);
console.log(reg2c);
var u = require('cloneRegExp');
var reg = /<a(?:.*?)href="([^\"]+)"(?:.*?)>(.*?)<\/a>/im;
var reg_cop = u.cloneRegExp(reg);
function test (str) {
console.log(reg.test(str));
console.log(reg_cop.test(str));
}
function match (str) {
var res = str.match(reg);
console.log(res);
var res2 = str.match(reg_cop);
console.log(res2);
}
[
'<a href="/hoge.org/hoge">hoge1</a>'
, '<a title="hoge2" href="/hoge.org/hoge2">hoge2</a>'
, '<a href="/hoge.org/hoge3" title="done">hoge3</a>'
].forEach(function (str, i) {
console.log('test %d', i + 1);
test(str);
match(str);
console.log();
});
/* result
test 1
true
true
[ '<a href="/hoge.org/hoge">hoge1</a>',
'/hoge.org/hoge',
'hoge1',
index: 0,
input: '<a href="/hoge.org/hoge">hoge1</a>' ]
[ '<a href="/hoge.org/hoge">hoge1</a>',
'/hoge.org/hoge',
'hoge1',
index: 0,
input: '<a href="/hoge.org/hoge">hoge1</a>' ]
test 2
true
true
[ '<a title="hoge2" href="/hoge.org/hoge2">hoge2</a>',
'/hoge.org/hoge2',
'hoge2',
index: 0,
input: '<a title="hoge2" href="/hoge.org/hoge2">hoge2</a>' ]
[ '<a title="hoge2" href="/hoge.org/hoge2">hoge2</a>',
'/hoge.org/hoge2',
'hoge2',
index: 0,
input: '<a title="hoge2" href="/hoge.org/hoge2">hoge2</a>' ]
test 3
true
true
[ '<a href="/hoge.org/hoge3" title="done">hoge3</a>',
'/hoge.org/hoge3',
'hoge3',
index: 0,
input: '<a href="/hoge.org/hoge3" title="done">hoge3</a>' ]
[ '<a href="/hoge.org/hoge3" title="done">hoge3</a>',
'/hoge.org/hoge3',
'hoge3',
index: 0,
input: '<a href="/hoge.org/hoge3" title="done">hoge3</a>' ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment