[英]Replace different characters using Regex
我想刪除字符串中一行的所有單個注釋//
和塊注釋/* */
。 但是,如果這些注釋位於字符''
、 ""
、 []
和/或``
,則不應將其刪除。
例子:
='a' &
'//b/*aasdsa //dsfds*/'& //comment
'//d' /*aasdsa //dsfds*/ & '//e' & /*aasdsa //dsfds*/
& 'c'
[// /* [] */] & h
`// /* [] */` & p
應該:
='a' &
'//b'&
'//d' & '//e' &
& 'c'
& h
& p
我嘗試了不同的解決方案,但我還沒有走得太遠。
let text = "='a' &
'//b'& //comment expression
'//d' /*aasdsa //dsfds*/ & '//e' & /*aasdsa //dsfds*/
& 'c'";
let arrayText = text.split('\n');
arrayText = arrayText.filter(a => a.indexOf('//') !== 0);
arrayContent = arrayContent.map(x =>
x.replace(/[^\(?<=\').*(?=\'$)|\(?<=\[).*(?=\]$](\/\*[\s\S]*?\*\/|\/\/.*)/gm, ''));
text = arrayContent.join(' ');
通過我嘗試的解決方案,我得到了以下內容:
文本:
='a' &
'//b/*aasdsa //dsfds*/'& //comment
'//d' /*aasdsa //dsfds*/ & '//e' & /*aasdsa //dsfds*/
& 'c'
[// /* [] */] & h
`// /* [] */` & p
我的解決方案的結果(不起作用)
='a' &
'//b'&
'//d' & '//e' &
& 'c'
[//]
預期結果:
='a' &
'//b/*aasdsa //dsfds*/'&
'//d' & '//e' &
& 'c'
[// /* [] */] & h
`// /* [] */` & p
如果有人能指出我遺漏的內容或任何其他提示,我將不勝感激。
正如評論中提到的,正則表達式不是通常由標記器完成的事情的合適工具。 對於這個特定用例,您可以編寫一個簡單的基於規則的解析器,如下所示:
const rules = [ { start: '[', end: ']', remove: false }, { start: "'", end: "'", remove: false }, { start: '"', end: '"', remove: false }, { start: '`', end: '`', remove: false }, { start: '//', end: {EOL:true}, remove: true }, { start: '/*', end: '*/', remove: true }, ]; function removeComments(str) { let start = -1, rule = null; //iterate over the input, character by character for(let i=0; i<str.length; i++) { if(!rule) { //if not currently in a 'group' (either string or comment) search for one let test = rules.find(r => str.slice(i).startsWith(r.start)); if(test) { rule = test; start = i; } } else { //currently in a string or comment, check if it ended let end = -1; if(str.slice(i).startsWith(rule.end)) { end = i + rule.end.length; } else if(rule.end.EOL && (str.slice(i).startsWith('\\n') || str.slice(i).startsWith('\\r\\n') || i == str.length - 1)) { //special handling for line comments which can end on many conditions end = i + 1; } if(end > -1) { if(rule.remove) { //modify str if it was a comment rule - cut out the comment str = str.slice(0,start) + str.slice(end); i -= end - start; } rule = null; } } } return str; } ["='a' &", "'//b/*aasdsa //dsfds*/'& //comment", "'//d' /*aasdsa //dsfds*/ & '//e' & /*aasdsa //dsfds*/", "& 'c'", "[// /* [] */] & h", "`// /* [] */` & p"].forEach(str => console.log(removeComments(str)));
請注意,輸出與您的預期輸出不同,因為您的預期輸出所做的事情違反了您在問題中制定的規則 - 它刪除了以[]
和 ```` 為邊界的所有內容。 以及包含在字符串'/* */'
塊注釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.