In the first sample I want to match Mortal
Input 1:
=Mortal
Regex 1:
=(.+)
Output 1:
MATCH 1
1. [1-7] `Mortal`
Works just as I want.
In the second sample, I want to match Mortal
and Combat
Input 2:
=Mortal/Combat
Regex 2:
=(.+)\/(.+)
Output 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 .
If I use =(.+)
on =Mortal/Combat
it matches:
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:
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.