'Regex for XML Schema
I just need help with a regular expression of a back camera of a mobile phone to put in my XML Schema but just can't seem to get it right. The issue is that some mobile phones have 4 cameras and some just two and I can't come up with a way to capture the whole group in one match and the changes that occur when having more cameras.
These are the strings I'm working with:
- 50 Mpx (f/1,88) + 13 Mpx (f/2,4) + 5 Mpx (f/2,4)
- 12 Mpx (f/1,6) + 12 Mpx (f/2,4)
- 64 Mpx (f/1,8) + 8 Mpx (f/2,3) + 2 Mpx (f/2,4) + 2 Mpx (f/2,4)
And this is the regex I came up with but doesn't match.
(\d+\sMpx\s\(f\/\d\,\d+\))(\s\+\s)*
Would you be able to transform my expression so it captures the strings above?
Thank you so much!
Solution 1:[1]
The pattern that you tried has 2 capture groups, which you do not need for a match only. As the pattern with Mpx is not repeated, you get separate matches.
The part (\s\+\s)* at the end is optional, and will also match trailing +
To get a single match, you can first match the first part with Mpx and then optionally repeat the + part followed by matching again the first part.
In the repetition you can use a non capture group (?: instead.
Note that you don't have to escape the comma, and depending on the regex delimiters you also don't have to escape the forward slash.
\d+\sMpx\s\(f\/\d,\d+\)(?:\s\+\s\d+\sMpx\s\(f\/\d,\d+\))*
Explanation
\d+\sMpx\s\(f\/\d,\d+\)Match 1+ digits, whitespace char,(f/, single digit, comma and 1+ digits(?:Non capture group\s\+\sMatch+between whitespace chars\d+\sMpx\s\(f\/\d,\d+\)Match the Mpx pattern again
)*Close the non capture group and optionally repeat it
See a regex demo.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | The fourth bird |
