使用正则表达式删除文本直到匹配的字符串

Remove the text until the matching string using regex

我在使用正则表达式删除字符串之前的所有内容时遇到问题。

给定的字符串:xyz@gmail.com No TEST NOTE. If you are not an intended recipient

预期结果:TEST NOTE. If you are not an intended recipient

我用来删除前面部分的正则表达式是[^*] * No

但它也删除了预期结果的一部分,结果给我 t an intended recipient

您正在使用贪婪的 *。尝试使用懒惰的 *?

我实际上不确定您的正则表达式如何删除 t an intended recipient 之前的所有内容。你可能希望你的正则表达式是

/^.*? No /i

如果电子邮件地址不一定在字符串的开头,^ 可能不是您想要的。

此外,如果您想删除 TEST NOTE 之前的所有内容,而不是 No 之前的所有内容,您可以尝试

/^.*?(?=TEST NOTE)/i

^str开始。 (.*?) 将匹配 No 之前的所有内容,不再匹配。第二组 (.*) 将匹配 No 之后的所有内容。 ""returns第二组

const str = "xyz@gmail.com No TEST NOTE. If you are not an intended recipient"
const res = str.replace(/^(.*?)No (.*)/, "")
console.log(res)

const str2 = "xyz@gmail.com No Not available in the store. Ask the seller. Item is NORM"
const res2 = str2.replace(/^(.*?)No (.*)/, "")
console.log(res2)

你的正则表达式如此工作是因为

  1. [^*] 表示除 * 之外的所有内容...并且您的字符串中没有 *
  2. 你正在使用 greedy *,所以它会竭尽全力直到 last 出现 no ] 在字符串中。
  3. 并且您显然使用了 i 标志,因此正则表达式中的 No 匹配 NoNOno.

这将完全匹配您要删除的部分:

^[^\s]+\sNo\s