0

I got strings which go:

abc123abc123abc123

abc123

abc123abc123abc123abc123abc123abc123

etc (varying units of abc123 which I don't know the length of repeat)

The task is to extract the first 1 and first a and the last c and last 3. Is it possible to do it with 1 regex and how exactly if it is possible? I kept count of the repeating units and based on the count I have been able to perform the task with a few regex, but would like to use one regex if possible. Thanks

Edit: In the real situation. It is more like a:(a number)bc:(a number)1:(a number)23:(a number) etc and I have to capture the first a number, the first 1 number, the last c number and the last 3 number.

Jeff

3
  • I don't quite understand. Do you want to find their positions? Because if you "extract" them, how does the first a differ from any other one? Commented Oct 29, 2012 at 0:19
  • 2
    In your examples, the first a is always at the start, the first 1 is always the fourth charachter, the last c is always the fourth from the rigth and the last c is the last character. So why dou you need a regex instead of x[0], x[3], x[-4] and x[-1]? Commented Oct 29, 2012 at 0:23
  • 1
    Yeah, please clarify your question a bit (with expected inputs -> outputs, and strings expected to not match (if any)..) Commented Oct 29, 2012 at 0:29

1 Answer 1

3

This is easiest done using two regexen. "^(a)bc(1)23" and "ab(c)12(3)$". It may be possible to merge these two, but the regular expression will get pretty unreadable.

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

2 Comments

I don't see the purpose of this? If the OP knows his string is a repetition of abc123 then your regexes will invariably return a, 1, c and 3.
I modelled the answer after the edit by OP. My example was not intended to be literal code, but to match the question of the OP.

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.