Reputation: 133
Lets say I have a sequence of numbers
1 2 3 4 1 2 3 4
As you can see there is a cycle here:
1 2 3 4
Now I am trying to make a regex expression to match a pattern. The pattern can be half the length of the sequence or 2 numbers long. This is what I have so far
Pattern cycle = Pattern.compile("((\\d+\\s)+(\\d+\\s))\\1");
I am given a string of numbers delimited by spaces. I am trying to use capture groups but not understanding it. Any help?
Upvotes: 0
Views: 4286
Reputation: 103
I am just trying to understand the question better. Is your problem similar to detecting a cycle/pattern in a given string ?
Something similar to this pattern ?
"([0-9]+?)\1+"
this pattern tries to capture a repeating pattern in a given stream of numbers.
Similar to the one discussed in this question What is wrong with my regex Pattern to find recurring cycles in Python?.
Upvotes: 0
Reputation: 121712
You can use this:
(\d(?:\s+\d)+)\s+\1
This will match two or more digits separated by spaces, capture it and look for what is captured right after another space character:
( # begin capturing group
\d # a digit, followed by
(?: # begin non capturing group
\s+ # one or more space characters, followed by
\d # a digit
)+ # end non capturing group, repeated once or more,
) # end capturing group `\1`, followed by
\s+ # one or more spaces, followed by
\1 # the exact content of the first captured group
Note: it assumes that the spacing is exactly the same in the repetition!
Upvotes: 3