简体   繁体   English

如何在正则表达式中全局匹配斜杠,除非它位于字符串的开头

[英]How to match slashes globally in regex except if it is at the start of the string

Hello stackoverflowers,你好stackoverflowers,

i couldn't figure the solution out by myself and couldn't find a related answer so i seek your help:)我自己想不出解决方案,也找不到相关的答案,所以我寻求你的帮助:)

I'm working in a VB.Net 4.x environment where i usualy have to join windows styled paths from various sources that are very unreliable in its format (leading slashes, ending slashes, sometimes double slashes inside) hence i can't use Path.Join我在 VB.Net 4.x 环境中工作,我通常必须加入来自各种来源的 windows 样式的路径,这些路径的格式非常不可靠(前导斜杠,结尾斜杠,有时内部有双斜杠)因此我不能使用Path.Join

My next best guess is to regex replace any double occurance of a backward slash with a single one: \\+我的下一个最佳猜测是正则表达式用单个反斜杠替换任何两次出现的反斜杠: \\+

which is too naive, as it also converts a server adress which starts with a leading double backslash.这太天真了,因为它还会转换以前导双反斜杠开头的服务器地址。

pseudocode伪代码

"\\server123\\a\\b\\\c\\".replace(/\\+/g, "\") -> "\server123\a\b\c"

thats a problem.那是个问题。 i want to exclude any leading backslashes from matching.我想从匹配中排除任何前导反斜杠。 So i though i negative lookahead it:所以我虽然我否定前瞻它:

regex正则表达式

(?!^\\+)\\+

which would work in my example.这将在我的示例中起作用。 But it does not what i want it to do.但这不是我想要的。 It matches the second backslash slash and replaces it.它匹配第二个反斜杠并替换它。

What is wrong with my second regex?我的第二个正则表达式有什么问题? how do i negative lookahead something at the start.我如何在一开始就否定前瞻某些东西。

Thanks for any explanation and solution感谢您的任何解释和解决方案

You can use您可以使用

Regex.Replace(text, "(?<!^\\*)\\+", "\")

See the .NET regex demo and the VB.NET online demo .请参阅.NET 正则表达式演示VB.NET 在线演示

Details :详情

  • (?<!^\\*) - a negative lookbehind that fails the match if, immediately to the left of the current location, there are any zero or more backslashes from the start of string (?<!^\\*) - 如果在当前位置的左侧紧邻字符串开头有任何零个或多个反斜杠,则匹配失败
  • \\+ - one or more backslashes. \\+ - 一个或多个反斜杠。

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

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