gpt4 book ai didi

javascript - 换行和5个新空格的正则表达式

转载 作者:行者123 更新时间:2023-11-28 03:05:45 25 4
gpt4 key购买 nike

我是 JavaScript 正则表达式新手任何帮助或提示将不胜感激!我有这个需求:\\.sp number\ ->结束当前输出行并跳过<number>垂直空间。 <number>是正整数或不存在。如果<number>不存在的,跳过一个空格。水平字符位置保持不变。

原文:

This is result level note five: This text is highlighted\.sp 5\This sentence should be displayed after 5 new lines.\.ce\This line should be centered.
This sentence should be on a new line.

新文本:

This is result level note five: This text is highlighted<br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; This sentence should be displayed after 5 new lines.\.ce\This line should be centered.
This sentence should be on a new line.

实现示例:

             test1 = test1.replace(/\\H\\/g,"<b>");
test1 = test1.replace(/\\N\\/g,"</b>");

最佳答案

您可以使用可选的捕获组来匹配数字,并通过替换使用回调函数。

检查组 1 是否已定义。如果是,请结合使用该组中的数字和例如 repeat 来生成替换字符串。

在演示中,我使用换行符作为替换。

\\\.sp (\d+)?\\

Regex demo

const regex = /\\\.sp (\d+)?\\/g;
const str = `This is result level note five: This text is highlighted\\.sp 5\\This sentence should be displayed after 5 new lines.\\.ce\\This line should be centered.
This sentence should be on a new line.

This is result level note without a number: This text is highlighted\\.sp \\This sentence should be displayed after 1 new lines.\\.ce\\This line should be centered.
This sentence should be on a new line.
`;
const result = str.replace(regex,
(_, g1) => g1 !== undefined ? "\n".repeat(parseInt(g1, 10)) : "\n\n"
);

console.log(result);

关于javascript - 换行和5个新空格的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60625738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com