[英]Regex optionally extracting characters between two characters
I have the following string thisIs/My-7777-Any-other-text
it also is possible for the following thisIs/My-7777
我有以下字符串thisIs/My-7777-Any-other-text
也可以用于以下thisIs/My-7777
I am looking to extract My-777
in both scenarios using regex.我希望在两种情况下都使用正则表达式提取My-777
。 So essentially I am looking to extract everything between the first forward flash and the second hyphen (Second hyphen may not exist).所以基本上我希望提取第一个前向 flash 和第二个连字符(第二个连字符可能不存在)之间的所有内容。 I tried the following regex which wasn't quite right我尝试了以下不太正确的正则表达式
(?<=\/)(.*)(?=-)
You could use a capture group您可以使用捕获组
^[^\/]*\/([^-]*-[^-]*)
^
Start of string ^
字符串开头[^\/]*\/
(
Capture group (
捕获组
[^-]*-[^-]*
Match a -
between optional chars that are not -
[^-]*-[^-]*
在不是-
的可选字符之间匹配-
)
Close capture group )
关闭捕获组Without an anchor, and not allowing /
before and after -
没有锚,并且不允许/
之前和之后-
[^\/]*\/([^-\/]*-[^-\/]*)
If we take into account the structure of your current input strings, you can use如果我们考虑到您当前输入字符串的结构,您可以使用
(?<=\/)[^-]+-[^-]+
See the regex demo .请参阅正则表达式演示。
If your strings are more complex and look like thisIs/My-7777/more-text-here
, and you actually want to match from the first /
, then you may use如果您的字符串更复杂并且看起来像thisIs/My-7777/more-text-here
,并且您实际上想从第一个/
匹配,那么您可以使用
^[^\/]+\/\K[^\/-]+-[^\/-]+ ## PHP, PCRE, Boost (Notepad++), Onigmo (Ruby)
(?<=^[^\/]+\/)[^\/-]+-[^\/-]+ ## JS (except IE & Safari), .NET, Python PyPi regex)
See this regex demo or this regex demo .请参阅此正则表达式演示或此正则表达式演示。 Note \n
is added in the demo since the input is a single multiline string, in real life input, if a newline char is expected, use it in each negated character class to keep matching on the one line.注意\n
在演示中添加,因为输入是单个多行字符串,在实际输入中,如果需要换行符,请在每个否定字符 class 中使用它以保持在一行上的匹配。
This one is working for me, Try it with case insensitive ticked这个对我有用,试试不区分大小写
Find what: .*?/|-any.*
查找什么: .*?/|-any.*
Replace with: blank
替换为: blank
Output should be ↠↠ My-7777
Output 应该是↠↠ My-7777
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.