0

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?

4
  • 1
    I don't think this problem can be easily solved with regex-es. Also what do you expect as an output for 1 2 3 4 1 2 3 Commented Jan 2, 2013 at 10:20
  • 1
    generally, if you have to "remember" something in pattern recognition, then regex is usually not the best choice. you'd be better of using a context-free automata Commented Jan 2, 2013 at 10:21
  • 3
    @izomorphius it can, don't forget the power of capturing groups ;) Commented Jan 2, 2013 at 10:27
  • As fge pointed out, regex implementations in most languages (including Java's) are somewhat more powerful than standard regular expressions, and can probably solve this. Commented Jan 2, 2013 at 10:32

2 Answers 2

3

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!

Sign up to request clarification or add additional context in comments.

Comments

0

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?.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.