[英]Match a string separated by slashes
In the first sample I want to match Mortal
在第一个样本中,我要匹配
Mortal
Input 1: 输入1:
=Mortal
Regex 1: 正则表达式1:
=(.+)
Output 1: 输出1:
MATCH 1
1. [1-7] `Mortal`
Works just as I want. 就像我想要的那样工作。
In the second sample, I want to match Mortal
and Combat
在第二个示例中,我要匹配
Mortal
和“ Combat
Input 2: 输入2:
=Mortal/Combat
Regex 2: 正则表达式2:
=(.+)\/(.+)
Output 2: 输出2:
MATCH 1
1. [1-7] `Mortal`
2. [8-14] `Combat`
Works just as I want. 就像我想要的那样工作。
My problem is that I want a solution that does both. 我的问题是我想要一个兼顾两者的解决方案。
If I use =(.+)\\/(.+)
on =Mortal
it matches nothing . 如果我在
=Mortal
上使用=(.+)\\/(.+)
=Mortal
=(.+)\\/(.+)
,则不会匹配任何内容 。
If I use =(.+)
on =Mortal/Combat
it matches: 如果我在
=Mortal/Combat
上使用=(.+)
,它将匹配:
MATCH 1
1. [1-14] `Mortal/Combat`
Both are incorrect. 两者都不正确。
Tried to merge them together: 试图将它们合并在一起:
=((.+)\/(.+)|(.+))
Which matches: 哪个匹配:
MATCH 1
1. [1-14] `Mortal/Combat`
2. [1-7] `Mortal`
3. [8-14] `Combat`
Or: 要么:
MATCH 1
1. [1-7] `Mortal`
4. [1-7] `Mortal`
Definitely incorrect. 绝对不正确。
Desired output should either be: 所需的输出应为:
MATCH 1
1. [1-7] `Mortal`
Or: 要么:
MATCH 1
1. [1-7] `Mortal`
2. [8-14] `Combat`
Would also be cool if it would be compatible with three slashes: =Mortal/Combat/X
should become: 如果它与三个斜杠兼容, 也将很酷 :
=Mortal/Combat/X
应该变为:
MATCH 1
1. [0-6] `Mortal`
2. [7-13] `Combat`
3. [14-15] `X`
How can I achieve this? 我该如何实现?
I am using http://regex101.com to test the regex. 我正在使用http://regex101.com来测试正则表达式。
This should work for all the three cases: 这应该适用于所有三种情况:
^=(.+)\/(.+)\/(.+)|=(.+)\/(.+)|=(.+)$
Explanation: 说明:
^ # Assert position at the beginning of the line
=(.+)\/(.+)\/(.+) # Three slashes
| # OR
=(.+)\/(.+) # Two slashes
| # OR
=(.+) # No slashes
$ # Assert position at the end of the line
=([^\/]+)\/?(.+)?
The ? ? make it optional.
将其设为可选。 This select everything before / for the first group.
这将选择第一组之前/之后的所有内容。 The rest are optional
其余均为可选
You can change the + with * if you want to match empty values also. 如果您还想匹配空值,则可以用*更改+。
Generic with supporting any amount of / 通用,支持任意数量的/
=(([^\/]+)\/?)*
Just look in group two for the values 只需在第二组中查找值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.