I need to a regres that find all single backslashes followed by an alphabet.
So I want to find backslashes that exist in patterns like these:
\a
\f
\test
and not in these patterns:
\\a
\"
Thanks
I need to a regres that find all single backslashes followed by an alphabet.
So I want to find backslashes that exist in patterns like these:
\a
\f
\test
and not in these patterns:
\\a
\"
Thanks
Updated:
As @Amadan points out in the comments below, JavaScript does not implement lookbehind, which basically breaks my original answer.
There is an approach suggested in this stackoverflow post that may be a reasonable path to take for this problem.
Basically the poster suggests reversing the string and using lookahead to match. If we were to do that, then we would want to match a string of alphabetic characters followed by a single backslash, but not followed by multiple backslashes. The regex for that would look like this:
/[a-zA-Z]+\\(?![\\]+)/g
[a-zA-Z]+ - match one or more alphabetic characters
\\ - followed by a single backslash
(?![\\]+) - not followed by one or more backslashes
g - match it globally (more than one occurrence)
The downside of this approach (aside from having to reverse your string) is that you can't match only the backslash, but will have to also match the alphabetic characters that come before it (since JS doesn't have lookbehind).
Original Answer (using lookbehind):
/(?<!\\)\\[a-zA-Z]+/g
(using negative lookbehind) will match a single backslash followed by one or more letters of the alphabet, regardless of case. This regular expression breaks down as follows:
(?<!\\)\\ - use negative lookbehind to match a \ that is not preceded by a \
[a-zA-Z]+ - match one or more letters of the alphabet, regardless of case
g - match it globally
If you only want to match the \
and not the alphabetic characters, then you can use positive lookahead. The regex for that would look like: /(?!>\\)\\(?=[a-zA-Z]+)/g
and would break down like this:
(?<!\\)\\ - use negative lookbehind to match a \ that is not preceded by a \
(?=[a-zA-Z]+) - and is followed by one or more alphabetic characters
g - match it globally
If you only want the regex to match backslashes at the beginning of a line, prepend a ^
to it.
You can use a tool like Rubular to test and play with regular expressions.