我想要匹配这几行,现在我使用多个正则表达式来匹配它们,但是我想知道是否可以在一个正则表达式中匹配两个:
@@Author:logan
//and these, three variations
@@tags:markdown,github,repetitivetag, tagwithsubtags:subtag, another:subtag:subtag2:repeating:this:repeating,repetitivetag,repetitivetag:withsubby,repetitivetag:withsubtag
@@tags:markdown;github;repetitivetag;tagwithsubtags:subtag,another:subtag:subtag2:repeating:this:repeating;repetitivetag;repetitivetag:withsubby;repetitivetag:withsubtag
@@tags:markdown;git-hub;repetitive-tag;tag_with_sub-tags:sub_tag,another:sub_tag:sub-tag2:repeating:this:repeat-_-_-ing;repetitive-tag;repetitive_tag:with_subby;repetitive_tag:with_subtag
我首先要做的是匹配@@NAME:VALUE
部分:
/^(?:@@)(\w+):(.*.)(?:\n+|$)/gm
假设第一组是NAME
,第二组是VALUE
。
如果NAME
为tags
,那么我会在VALUE
中匹配以下正则表达式:
/(\w+)((?=,|;)|(:\w[\w|\-]+\w){0,}|)/g
这与我们之前匹配的TAG;TAG;TAG ...
中的TAG,TAG,TAG ...
或VALUE
的几个组相匹配
然后我将每个TAG
与此匹配,以获得SUBTAG
/(:)(\w[\w|\-]+\w)(?=:|)/g
现在匹配:SUBTAG:SUBTAG:SUBTAG ...
中TAG
之类的群组(我们在上面匹配
我想匹配
(@@)(NAME)(:)(VALUE)
(TAG)(;)(TAG)(;)(TAG) ...
(:)(SUBTAG)(:)(SUBTAG))(;)
@@Author:logan
应该能够获得Name = Author
,Value = logan
如果值是多个,例如,如果用逗号或分号分隔,那么匹配@@tags:tag1;tag2
之类的东西应该能够获得
Name = Tags
,`值= ['tag1','tag2']
如果值具有子值,例如
@@Author:logan:lastname
或此作为其预期目的
@@Tags:tag1:subtag;tag2:subtag1:subtag2
应该能够获得:
Name = Author
,Value = [{logan : [lastname]}]
和
Name = Tags
,Value = [{tag1 : [subtag]}, {tag2 : [subtag1, subtag2]}]
我如何匹配群组内的群组,只有它们存在?
答案 0 :(得分:2)
这准确地给出了你想要的输出:
// Examples:
var a='@@Author:logan';
var b='@@tags:tag1;tag2';
var c='@@Author:logan:lastname';
var d='@@Tags:tag1;tag2:subtag1:subtag2';
var hard1='@@tags:markdown,github,repetitivetag, tagwithsubtags:subtag, another:subtag:subtag2:repeating:this:repeating,repetitivetag,repetitivetag:withsubby,repetitivetag:withsubtag';
var hard2='@@tags:markdown;github;repetitivetag;tagwithsubtags:subtag,another:subtag:subtag2:repeating:this:repeating;repetitivetag;repetitivetag:withsubby;repetitivetag:withsubtag';
var hard3='@@tags:markdown;git-hub;repetitive-tag;tag_with_sub-tags:sub_tag,another:sub_tag:sub-tag2:repeating:this:repeat-_-_-ing;repetitive-tag;repetitive_tag:with_subby;repetitive_tag:with_subtag';
function tags(a){
// Gets the name:
var name=a.match(/^@@.*?(:|.$)/);
if(!name) return;
var temp=a.indexOf(':')+1;
name=name[0].substring(2).replace(':','');
// Returns the name if thats all there is:
if(!temp) return name;
a=a.substring(temp);
// Gets the value:
var value=a.split(/[,;]/);
if(value.length==1&&value[0].indexOf(':')==-1)
value=value[0];
else for(var i=0;i<value.length;i++) if(value[i].indexOf(':')!=-1) {
// Gets the subtags if they exist:
temp={};
a=value[i].split(':');
// .shift() will remove/return the first of the array
temp[a.shift()]=a;
value[i]=temp;
}
return {name:name,value:value};
}
console.log([tags(a),tags(b),tags(c),tags(d),tags(hard1),tags(hard2),tags(hard3)]);
实际编码真的很酷。我不确定你的问题是否说明了你想要的东西,但如果没有,那么一切都应该很容易修改。希望你喜欢else-for-if声明!