正则表达式替换单个反斜杠,不包括后面跟着某些字符的反斜杠
我有一个正则表达式,如果后面没有这些字符之一,它会从字符串中删除任何反斜杠:\ / 或 }。
它应该把这个字符串:
foo\bar\\batz\/hi
变成这样:
foobar\\batz\/hi
但问题是它在处理每个反斜杠时。因此它遵循的规则是删除第一个反斜杠,并忽略第二个反斜杠,因为它后面跟着另一个反斜杠。但是当它到达第三个时,它会将其删除,因为它后面没有另一个。
我当前的代码如下所示: str.replace(/\\(?!\\|\/|\})/g,"")
但生成的字符串如下所示: foobar\batz\/hi
如何让它跳过第三个反斜杠?或者是进行某种明确的否定搜索和搜索的情况?替换类型的东西?例如。替换 '\',但不替换 '\\'、'\/' 或 '\}'?
请帮忙! :)
编辑
抱歉,我应该解释一下 - 我正在使用 javascript,所以我不认为我可以做负面的lookbehinds...
I have a regex expression which removes any backslashes from a string if not followed by one of these characters: \ / or }.
It should turn this string:
foo\bar\\batz\/hi
Into this:
foobar\\batz\/hi
But the problem is that it is dealing with each backslash as it goes along. So it follows the rule in that it removes that first backslash, and ignores the 2nd one because it is followed by another backslash. But when it gets to the 3rd one, it removes it, because it isn't followed by another.
My current code looks like this: str.replace(/\\(?!\\|\/|\})/g,"")
But the resulting string looks like this: foobar\batz\/hi
How do I get it to skip the 3rd backslash? Or is it a case of doing some sort of explicit negative search & replace type thing? Eg. replace '\', but don't replace '\\', '\/' or '\}'?
Please help! :)
EDIT
Sorry, I should have explained - I am using javascript, so I don't think I can do negative lookbehinds...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要注意转义的反斜杠,后跟一个反斜杠。或者更好:连续反斜杠的数量不均匀。在这种情况下,您需要保持偶数个反斜杠完整,并且仅替换最后一个(如果后面没有
/
或{
)。您可以使用以下正则表达式:
并将其替换为:
其中第一个匹配组是匹配的第一个偶数个反斜杠。
简短的解释:
用简单的英语来说:
Java 中的演示(请记住反斜杠是双转义的!):
它将打印:
EDIT
不需要后向查找的解决方案如下所示:
并替换为:
其中
$1
是开头的非反斜杠字符,$2
是该非反斜杠字符后面的偶数(或零)个反斜杠。You need to watch out for an escaped backslash, followed by a single backslash. Or better: an uneven number of successive backslashes. In that case, you need to keep the even number of backslashes intact, and only replace the last one (if not followed by a
/
or{
).You can do that with the following regex:
and replace it with:
where the first match group is the first even number of backslashes that were matched.
A short explanation:
In plain ENglish that would read:
A demo in Java (remember that the backslashes are double escaped!):
which will print:
EDIT
And a solution that does not need look-behinds would look like:
and is replaced by:
where
$1
is the non-backslash char at the start, and$2
is the even (or zero) number of backslashes following that non-backslash char.所需的正则表达式就像
\\.
一样简单,但是您需要知道,
replace()
的第二个参数可以是如下函数:The required regex is as simple as
\\.
You need to know however, that the second argument to
replace()
can be a function like so:您需要像您一样先行查找,也需要后行查找,以确保不会删除第二个斜杠(显然后面没有特殊字符。试试这个:
(? 作为你的正则表达式
You need a lookahead, like you have, and also a lookbehind, to ensure that you dont delete the second slash (which clearly doesnt have a special character after it. Try this:
(?<![\\])[\\](?![\\\/\}])
as your regex