简体   繁体   中英

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 \\: .

Match: :Amazing

No match: \\:Amazing

I tried [^\\\\](:Amazing) , but it also matches x:Amazing

I want to replace string Hello, this is :Amazing and also \\:Amazing

with 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

Note: This works in PHP PCRE

Live demo

JavaScript doesn't support lookbehinds (only Google Chrome as of now). To have it in JS too you need something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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