[英]javascript: regexp to match a word that is NOT enclosed in custom tags
我需要匹配並替換所有未包含在字符串:$
和$:
中的'word'單詞。 標簽中的“單詞”旁邊可能還有其他字符。
所以,說我有字符串
abc word hey :$ my word $:
而且我需要用letter
代替word
; 本質上,我想獲取以下字符串:
abc letter hey :$ my word $:
用JavaScript實現這一目標的最佳方法是什么?
更多信息:
標簽不會嵌套。 該字符串可以包含單個字符“:”和“ $”。 在這種情況下,應將它們視為簡單字符而不是標簽。
我無法為此指定RegExp,因此這是一種更強制性的方法-http://jsfiddle.net/dNhLm/
var text = "abc word hey :$ my word $:";
var replace = function(text, pattern, replacement) {
var parts = [];
// This will split the string into parts. The ones that has :$ we will have to proceed further and ignore
var splitByEnd = text.split('$:');
for (i = 0, l = splitByEnd.length; i < l; i++) {
// Here we should have at most 2 parts. The left one will be outside of the :$,$: pairs and is the
// one we will apply the replacement. The right one if present will be between the :$,$: pairs and is
// not a subject of replacement.
var splitByStart = splitByEnd[i].split(':$');
splitByStart[0] = splitByStart[0].replace(pattern, replacement);
parts.push(splitByStart.join(':$'));
}
return parts.join('$:');
}
alert(replace(text, 'word', 'letter'));
我不確定正則表達式是否適合此處的工作(解析器可能更合適),但是我猜一個簡單的解決方案是切掉標簽所覆蓋的位,替換所有單詞,然后替換標簽。 與此類似的東西(它不支持嵌套標簽,但應該可以工作):
var line = 'abc word hey :$ my word $: word :$ my word $:';
var tags = [];
var index = 0;
while (line.match(/:\$.*\$:/)) {
var start = line.indexOf(':$');
var end = line.indexOf('$:', start);
var tag = line.substring(start, end + 2);
line = line.replace(tag, '$tag' + index + '$');
tags.push(tag);
index++;
}
line = line.replace(/word/g, 'letter');
for (var i = 0; i < tags.length; i++) {
line = line.replace('$tag' + i + '$', tags[i]);
}
document.write('result ' + line)
輸出:
result abc letter hey :$ my word $: letter :$ my word $:
^(.+?)?(:\$.+?\$:)(.+?)?$
這將為您提供三個捕獲組:
:?
和?:
:?
和?:
然后,您想在第一個和第三個捕獲組上執行通常的stringreplace,將word
替換為letter
。
第一組和第三組對於:?word?: another word
是可選的:?word?: another word
也將匹配。
var regex = /^(.+?)?(:\$.+?\$:)(.+?)?$/i;
regex.exec('abc word hey :$ my word $:');
alert(RegExp.$1.replace("word", "letter") + RegExp.$2 + RegExp.$3.replace("word", "letter"));
我能想到的是,沒有簡單的正則表達式。
您可以查找多個正則表達式
var s1 = 'abc word hey :$ my word $: def word :$ another word $: word ghi :$ a third word $: jkl word';
var s2;
// word at the beginning
s2 = s1.replace(/^([^:$]*)word/, '$1letter');
// word at the end
s2 = s1.replace(/word([^:$]*)$/, 'letter$1');
// and word in between
s2 = s1.replace(/(:[^$]*)word([^$]*:)/g, '$1letter$2');
console.log(s2);
參見JSFiddle
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.