$などの特殊文字と文字列の単語を一致させます!そしてそれらを交換

サジット・クマール・シン

次のように入力文字列に処理する必要があります -

// 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>

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=320319&siteId=1
おすすめ