更换某个字符串开头和结尾的字符

3
假设有以下字符串:
b*any string here*

如果存在这种情况,我想把开头的b*替换为<b>,并把结尾的*替换为</b>(请忽略反斜杠,我在SO网站上需要它来转义)。

此外,可能会有多个匹配:

b*any string here* and after that b*string b*.

不应处理这些情况:

b*foo bar
foo bar*
bb*foo bar* (b is not after a whitespace or beginning of string).

我已经做到了这一步:

(?<=b\*)(.*?)(?=\*)

这让我得到了其中的字符串,但我在进行交换时遇到了困难。

1
“忽略反斜杠,我需要它来在 SO 网站上进行转义” - 不,你不需要。将您想要显示为代码的任何内容包装在反引号字符中:\your html entities/code here``以将其显示为代码。 - David Thomas
环视是非消耗性的,使用“正则表达式”,非消耗性模式:/\bb\*(.*?)\*/g,并用<b>$1</b>替换。或者,如果你真的想要一个空格边界,可以使用.replace(/(^|\s)b\*(.*?)\*/g, "$1<b>$2</b>") - Wiktor Stribiżew
抱歉,我的意思是“常规的”,消费模式。 - Wiktor Stribiżew
2个回答

3
使用 String#replace 方法,你只需要捕获要保留的文本即可。
var result = theString.replace(/\bb\*(.*?)\*/g, "<b>$1</b>");

在正则表达式开头的\b表示单词边界,这样它只匹配不属于单词的b$1表示第一个捕获组(.*?)

示例:

var str1 = "b*any string here* and after that b*string b*.";

var str2 = `b*foo bar
foo bar*
bb*foo bar* (b is not after a whitespace or beginning of string).`;

console.log(str1.replace(/\bb\*(.*?)\*/g, "<b>$1</b>"));

console.log(str2.replace(/\bb\*(.*?)\*/g, "<b>$1</b>"));


肯定不是我点了踩。str1很好,但为什么即使在第二行(foo bar *)后面加上一个空格,str2也不能工作呢? - ddy250
@ddy250,我刚刚测试了一下,它可以正常工作。你确定吗?... b b*text*按预期工作。 - ibrahim mahrir
也许只是我测试的环境问题。无论如何,这只是一个我不太需要的角落。 - ddy250

0

дҪ еҸҜд»ҘдҪҝз”Ё\b(?:b\*)(.+?)(?:\*)пјҢиҝҷж ·

const result = yourString.replace(/\b(?:b\*)(.+?)(?:\*)/, "<b>$1</b>");

请查看“替换”选项卡https://regexr.com/447cq


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接