Reputation: 7491
I have a problem solving this: http://regexone.com/lesson/13
I was trying to do something like: (\d+x\d+)
but why it doesn't work? How do we use "grouping" anyway? Thanks!
input text required capturing group result
1280x720 1280, 720
1920x1600 1920, 1600
1024x768 1024, 768
Upvotes: 2
Views: 181
Reputation: 44488
You want two specific things to match - the x and the y resolution. That means, you need two groups.
So, you know you need: ()()
You don't want the x captured and the x sits between what you want captured:
()x()
Finally, we need to fill in what we're searching for. We want one or more (+) digits (\d). Therefore, the completed regex is:
(\d+)x(\d+)
Upvotes: 1
Reputation: 726987
The exercise is about capturing groups. The requirement is to capture two sequences of digits separately, and skip the x
, like this:
(\d+)x(\d+)
Your solution, on the other hand, captures the entire input into a single capturing group denoted by parentheses.
The concept of capturing groups is very important when you need to process individual parts of the input captured by your regular expression, as opposed to processing the entire capture. In the examples at your link, you can grab the first group for the horizontal component of the resolution, and the second group for the vertical component of the resolution. Without two separate capturing groups you would need to find x
in your code, and do an additional split.
Upvotes: 1
Reputation: 4608
Capturing group are surrounded by brackets (
and )
.
In your regex (\d+x\d+)
, there is one capturing group - the entire \d+x\d+
thing, because the entire regex is surrounded by a capturing group.
In that question particular, you want to get two separate numbers. So, one group shall "capture" a number and the other group "capture" the another number.
So, for the first group, you would be capturing the first number (character sequence) only - (\d+)
. Same goes to the second.
In addition, you need not the x
, so you would put it outside of any capturing groups.
Hence, (\d+)x(\d+)
would be what you want.
Upvotes: 1