另一个选择中的正则表达式选择
Regex selection in another selection
所以我有这样一个字符串:
var a = " 'asdf'+'asdf'+'we' + 1";
我可以 select 三个引号:
'([^']*)'
如何使用正则表达式 select 字符串中单引号 (') 的开头?
还有一个单独的正则表达式 select 单引号 (') 的结尾?正则表达式可能吗?我将用 <<.
替换引号的开头
最终字符串看起来像
" <<asdf'+<<asdf'+<<we' + 1"
当你只需要替换模式的某些部分时,在你需要保留的部分周围使用捕获组,并且只匹配(并消耗)你需要删除的部分。
var a = " 'asdf'+'asdf'+'we' + 1";
console.log(
a.replace(/'([^']*')/g, '<<')
);
// And, to replace both ' in one go (notice the ) shift to the left):
console.log(
a.replace(/'([^']*)'/g, '<<>>')
);
这里,
'
- 匹配并消耗 '
([^']*')
- 将 捕获 匹配到第 1 组零个或多个 '
以外的字符(使用 [^']*
),然后是 '
。替换模式中的 </code> 是找到有效匹配后存储在第 1 组中的内容的占位符。</li>
<li><code>([^']*)
- 仅将 '
以外的任何 0+ 个字符捕获到第 1 组中,因此最终的 '
被匹配和消耗,并且将在
占位符内容。
另请参阅 regex demo 1 and regex demo 2。
所以我有这样一个字符串:
var a = " 'asdf'+'asdf'+'we' + 1";
我可以 select 三个引号:
'([^']*)'
如何使用正则表达式 select 字符串中单引号 (') 的开头? 还有一个单独的正则表达式 select 单引号 (') 的结尾?正则表达式可能吗?我将用 <<.
替换引号的开头最终字符串看起来像
" <<asdf'+<<asdf'+<<we' + 1"
当你只需要替换模式的某些部分时,在你需要保留的部分周围使用捕获组,并且只匹配(并消耗)你需要删除的部分。
var a = " 'asdf'+'asdf'+'we' + 1";
console.log(
a.replace(/'([^']*')/g, '<<')
);
// And, to replace both ' in one go (notice the ) shift to the left):
console.log(
a.replace(/'([^']*)'/g, '<<>>')
);
这里,
'
- 匹配并消耗'
([^']*')
- 将 捕获 匹配到第 1 组零个或多个'
以外的字符(使用[^']*
),然后是'
。替换模式中的</code> 是找到有效匹配后存储在第 1 组中的内容的占位符。</li> <li><code>([^']*)
- 仅将'
以外的任何 0+ 个字符捕获到第 1 组中,因此最终的'
被匹配和消耗,并且将在占位符内容。
另请参阅 regex demo 1 and regex demo 2。