如何用JS正则提取字符串中第n个$分隔符后的指定内容?
提取第三个$分隔的内容方案
方法一:字符串分割(简单直观)
直接按$分割字符串,取对应位置的元素再去除前后空格即可,代码示例(以JavaScript为例,适配Discord.js场景):
const inputStr = "$command this my first text $ this is my second text $ this is my third text $ this is my fourth text"; const segments = inputStr.split('$'); // 分割后数组的第3项(索引从0开始)就是目标内容所在的片段 const targetContent = segments[3].trim(); console.log(targetContent); // 输出:this is my third text
分割后的数组结构为:["", "command this my first text ", " this is my second text ", " this is my third text ", " this is my fourth text"],索引3的元素就是第三个$对应的内容片段,trim()用于去除前后多余空格。
方法二:正则表达式匹配
如果一定要用正则,需要精准匹配前两个$分隔的内容,再捕获第三个$与第四个$之间的文本,修正后的正则如下:
const inputStr = "$command this my first text $ this is my second text $ this is my third text $ this is my fourth text"; const regex = /^\$.*?\$.*?\$\s*(.*?)\s*\$/; const matchResult = inputStr.match(regex); if (matchResult) { console.log(matchResult[1]); // 输出:this is my third text }
正则说明:
^\$:匹配字符串开头的第一个$.*?\$:非贪婪匹配第一个$到第二个$之间的所有内容,再匹配第二个$.*?\$:继续非贪婪匹配第二个$到第三个$之间的内容,再匹配第三个$\s*(.*?)\s*\$:匹配第三个$后的空格,捕获中间的目标文本,再匹配第四个$前的空格和第四个$
你之前的正则(?:\$){2}(\s.*)之所以失败,是因为它仅匹配连续两个$,然后捕获后续所有文本,无法精准定位到第三个$对应的片段。
内容的提问来源于stack exchange,提问作者user874737
相关产品推荐
相关产品推荐

