サジット・クマール・シン
次のように入力文字列に処理する必要があります -
// Input string -
'My pen cost is !!penCost!! manufactured in $$penYear$$ with colors !!penColor1!! and $$penColor1$$'
// Processed string
'My pen cost is <penCost> manufactured in <penYear> with colors <penColor1> and <penColor1>'
、私が管理しているが、ループを使用して、それを行うが、正規表現のアプローチを知ることに興味を持っています。これは、(非稼働状態で)私の実験の現在の状態です -
const regex = /\b(\w*([a-zA-Z])|([\!]{2}[a-zA-Z][\!]{2})\w*)\b/g;
// str is holding the input string
str.replace(regex, (match) => {
return `<${match.substring(2, match.length - 2)}>`;
});
私のような値を持つ適切に一致する単語に正規表現に捕まってしまった "$$ [-ZA-Z0-9] $$" または "!! [-ZA-Z0-9] !!"。
anubhava:
あなたは使用することができます:
str = str.replace(/(!!|\$\$)([\w-]+)\1/g, '<$2>');
正規表現の詳細:
(!!|\$\$)
一致!!
または$$
グループ#1に、キャプチャ([\w-]+)
マッチ1+グループ2位に単語またはハイフン文字とキャプチャ\1
:グループ#1と同じ開始区切り文字と必ず文字列の両端を作ります- 交換がある
<$2>
中で、グループ2位で文字列をラップする<
と、>
コード:
const str = 'My pen cost is !!penCost!! manufactured in $$penYear$$ with colors !!penColor1!! and $$penColor1$$';
const res = str.replace(/(!!|\$\$)([\w-]+)\1/g, '<$2>');
console.log(res);
//=> My pen cost is <penCost> manufactured in <penYear> with colors <penColor1> and <penColor1>