PowerShell - regex to get string between two strings

霸气de小男生 提交于 2019-12-10 16:47:59

问题


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

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

For example:

Full String = //Manhattan/Project

Output = Manhattan

Any help will be very much appreciated.


回答1:


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

//([^/]+)/

Explanation:

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



回答2:


You could use the below regex which uses lookarounds.

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



回答3:


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):

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


来源:https://stackoverflow.com/questions/26345738/powershell-regex-to-get-string-between-two-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!