contenteditable div id = "board_code_dup"
cout<<"something";
if( a>b && b<c ){
cout<<"hi";
if( a==0 )
cout<<"hello";
}
else if( a<b )
cout<<"yow";
else{
cout<<"not here";
cout<<"sure";
}
cout<<"something";
条件付きブロックをラップしたかった:
1
if( a>b && b<c ) {
cout<<"hi";
if(a ==0 )
cout<"hello";
}
2
if( a==0 )
cout<<"hello";
3
else if( a<b )
cout<<"yow";
4
else{
cout<<"not here";
cout<<"sure";
}
ターゲット HTML は次のようになります。
<div id = "board_code_dup">
<div>cout<<"something";</div>
<div><span class="condBlock">if(a>b && b<c ){</div>
<div>cout<<"hi";</div>
<div><span class="condBlock">if(a==0)</div>
<div>cout<<"hello";</span></div>
<div>}</span></div>
<div><span class="condBlock">else if(a<b)</div>
<div>cout<<"yow";</span></div>
<div><span class="condBlock">else{</div>
<div>cout<<"not here";</div>
<div>cout<<"sure";</div>
<div>}</span></div>
<div>cout<<"something"</div>
</div>
問題condBlock ラッピングを達成するための正しい正規表現は何ですか?
text = text.replace(/(if[\s\S]*;)/g, '<span class="frag condBlock">$1</span>');
実装これは私の実際のコードです。条件付きフラグメントとしてcout<<"something"
,cin>>variable and (b>a)
をラッピングするなど、他のラッピングはすでに成功しています( (a>b) && (a<b) )
$('#board_code_dup').children().each(function (index, child) {
var text = $(child).html();
text = text.replace(/(#include(\s*<.*>)?)/g, '<span class="frag">$1</span>');
text = text.replace(/(main)/g, '<span class="frag">$1</span>');
text = text.replace(/(else(?!\s+if))/g, '<span class="frag cond">$1</span>');
text = text.replace(/([A-Za-z0-9_]+=[A-Za-z0-9_]+)/g, '<span class="frag">$1</span>');
text = text.replace(/(clrscr[^;]*;)/g, '<span class="frag">$1</span>');
text = text.replace(/(getch[^;]*;)/g, '<span class="frag">$1</span>');
text = text.replace(/(cout\s*(<<\s*[^;&]*\s*)*;)/g, '<span class="frag">$1</span>');
text = text.replace(/(cin\s*(>>\s*[^;&]*\s*)*;)/g, '<span class="frag">$1</span>');
text = text.replace(/((int|char|float|bool)[^;]+;)/g, '<span class="frag">$1</span>');
text = text.replace(/(if[\s\S]*;)/g, '<span class="frag condBlock">$1</span>');
if(var_int.length>0){
var r1 = '\\b(' + var_int.join('|') + ')\\b';
var myRegex1 = new RegExp(r1, 'g');
text = text.replace(myRegex1, '<span class="frag">$1</span>');
}
if(var_char.length>0){
var r2 = '\\b(' + var_char.join('|') + ')\\b';
var myRegex2 = new RegExp(r2, 'g');
text = text.replace(myRegex2, '<span class="frag">$1</span>');
}
if(var_float.length>0){
var r3 = '\\b(' + var_float.join('|') + ')\\b';
var myRegex3 = new RegExp(r3, 'g');
text = text.replace(myRegex3, '<span class="frag">$1</span>');
}
if(var_bool.length>0){
var r4 = '\\b(' + var_bool.join('|') + ')\\b';
var myRegex4 = new RegExp(r4, 'g');
text = text.replace(myRegex4, '<span class="frag">$1</span>');
}
if(var_condSet.length>0){
var r4 = '\\b(' + var_condSet.join('|') + ')\\b';
var myRegex4 = new RegExp(r4, 'g');
text = text.replace(myRegex4, '<span class="frag">$1</span>');
}
$(child).html(text);
});