PowerShell - 正则表达式在两个字符串之间获取字符串

时间:2022-09-10 14:08:49

I'm not very experienced in Regex. Can you tell me how to get a string value from between two strings?

我在正则表达方面不是很有经验。你能告诉我如何从两个字符串之间获取字符串值吗?

The subject will always be in this format : //subject/some_other_stuff

主题将始终采用以下格式:// subject / some_other_stuff

I need to get the string found between // and /.

我需要在//和/之间找到字符串。

For example:

Full String = //Manhattan/Project

Full String = // Manhattan / Project

Output = Manhattan

输出=曼哈顿

Any help will be very much appreciated.

任何帮助将非常感谢。

3 个解决方案

#1


5  

You can use a negated character class and reference capturing group #1 for your match result.

您可以使用否定字符类并引用捕获组#1作为匹配结果。

//([^/]+)/

Explanation:

//         # '//'
(          # group and capture to \1:
  [^/]+    #   any character except: '/' (1 or more times)
)          # end of \1
/          # '/'

#2


2  

You could use the below regex which uses lookarounds.

你可以使用下面使用lookarounds的正则表达式。

(?<=\/\/)[^\/]+(?=\/)

#3


2  

Since the strings are always of the same format, you can simply split them on / and then retrieve the element at index 2 (the third element):

由于字符串总是具有相同的格式,您可以简单地将它们拆分为/,然后在索引2处检索元素(第三个元素):

PS > $str = "//Manhattan/Project"
PS > $str.split('/')[2]
Manhattan
PS > $str = "//subject/some_other_stuff"
PS > $str.split('/')[2]
subject
PS >

#1


5  

You can use a negated character class and reference capturing group #1 for your match result.

您可以使用否定字符类并引用捕获组#1作为匹配结果。

//([^/]+)/

Explanation:

//         # '//'
(          # group and capture to \1:
  [^/]+    #   any character except: '/' (1 or more times)
)          # end of \1
/          # '/'

#2


2  

You could use the below regex which uses lookarounds.

你可以使用下面使用lookarounds的正则表达式。

(?<=\/\/)[^\/]+(?=\/)

#3


2  

Since the strings are always of the same format, you can simply split them on / and then retrieve the element at index 2 (the third element):

由于字符串总是具有相同的格式,您可以简单地将它们拆分为/,然后在索引2处检索元素(第三个元素):

PS > $str = "//Manhattan/Project"
PS > $str.split('/')[2]
Manhattan
PS > $str = "//subject/some_other_stuff"
PS > $str.split('/')[2]
subject
PS >