简体   繁体   English

匹配以 : 字符开头但不以 \\ 开头的字符串:

[英]Match a string starting with : character, but not starting with \:

I need a RegEx to replace a word in a long string starting with a single : , but not starting with \\: .我需要一个 RegEx 来替换以单个:开头但不以\\:开头的长字符串中的单词。

Match: :Amazing匹配:Amazing

No match: \\:Amazing不匹配: \\:Amazing

I tried [^\\\\](:Amazing) , but it also matches x:Amazing我试过[^\\\\](:Amazing) ,但它也匹配x:Amazing

I want to replace string Hello, this is :Amazing and also \\:Amazing我想替换字符串Hello, this is :Amazing and also \\:Amazing

with Hello, this is COOL and also :Amazing Hello, this is COOL and also :Amazing

Thank you.谢谢你。

You are telling that you don't need any character after : .您是在告诉您在:之后不需要任何字符。 You need a negative look-behind for this:您需要对此进行负面回顾:

:(?<!\S.)Amazing
  • \\S means a non-whitespace character \\S表示非空白字符

Note: This works in PHP PCRE注意:这适用于 PHP PCRE

Live demo现场演示

JavaScript doesn't support lookbehinds (only Google Chrome as of now). JavaScript 不支持后视(目前仅支持 Google Chrome)。 To have it in JS too you need something like this:要在 JS 中也有它,你需要这样的东西:

 var str = `Hello, this is :Amazing and also \\\\:Amazing x:Amazing`; console.log(str.replace(/(^|\\s):Amazing/g, "$1COOL"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM