正则表达式匹配字符串中所有相对路径

huangapple go评论56阅读模式
英文:

regular-expressions to match all the relative path in string

问题

你可以使用以下正则表达式来过滤相对路径格式的字符串:

ser_ver[\\\/][\w-]+([\\\/][\w-]+)*\.dat

请注意,这个正则表达式假设你的字符串中的反斜杠和斜杠都可以用\\\/来表示。

英文:

How to write a regex to filter all the string with relative path format i.e.starts with ser_ver/ and ends with .dat and inbetween may have _,-,/ like following,

file1 ser_ver\sha-re\subfolder_1.dat
file2 ser_ver\sha-re\folder1\subfolder_1\subfolder_2.dat
file3 server\sha-re\complex\subfolder_1.dat
file4 server\sha-re55AB12\subfolder_1\subfolder_2\subfolder_3.dat

expected:

ser_ver\sha-re\subfolder_1.dat
ser_ver\sha-re\folder1\subfolder_1\subfolder_2.dat

答案1

得分: -1

以下是翻译好的部分:

/\bser_ver\/[\w\/-]+\.dat\b/

解释...

\b

零宽度单词边界,匹配在“单词”和“非单词”字符之间。实际上不会增加匹配内容,只是将其锚定,以确保匹配不会在单词中间开始或结束。

[\w\/-]+

匹配一个或多个字符,包括从a到z,A到Z,下划线,短横线或正斜杠。

\.

字面上的 `.`。

所以它匹配...

\b ser_ver/ [\w\/-]+ .dat \b

单词边界,然后是 `ser_ver/`,然后是一个或多个字符,包括从a到z,A到Z,下划线,短横线或正斜杠,然后是 `.dat`,最后是另一个单词边界。

所有这些假设你在注释中使用正斜杠。

正如评论中的某人提到的,你的示例实际上使用反斜杠,所以如果你在使用反斜杠,需要进行更新。

像这样...

/\bser_ver\\[\w\\-]+\.dat\b/

或者允许两种都使用...

/\bser_ver[\\\/][\w\\\/-]+\.dat\b/

请告诉我如果需要任何进一步的帮助。

英文:

Something like this...

/\bser_ver\/[\w\/-]+\.dat\b/

Explanation...

\b

Zero-width word boundary, matches between a "word" and "non-word" character. Doesn't actually add anything to the match, just anchors it so it can't start or end in the middle of a word.

[\w\/-]+

Matches one or more characters from a to z, A to Z, underscore, dash or forward slash.

\.

Literal ..

So it matches...

\b ser_ver/ [\w\/-]+ .dat \b

Word boundary followed by ser_ver/ then one or more characters from a to z, A to Z, underscore, dash or forward slash, followed by .dat and then another word boundary.

All this assumes that you're working with forward slashes as stated in your comments.

As mentioned by someone else in the comments, your examples actually use backslash, so this would need updating if you're using those.

Like this...

/\bser_ver\\[\w\\-]+\.dat\b/

Or allow both...

/\bser_ver[\\\/][\w\\\/-]+\.dat\b/

huangapple
  • 本文由 发表于 2023年4月19日 22:59:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76056014.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定