1

Looking for a regular expression that extracts multiple characters, at different locations, in my string. For example, the string I'm working with is 5490028400316201600008 and it will always be this same length, but the numbers can change.
I would like to extract the first 9 characters, then skip the next 8, extract the next 4, then ignore the last character. The resulting string would be 5490028400000 in this case. I can't seem to find an easy way to do this and I'm fairly new to regular expressions. Thanks in advance for your advice/help.

3
  • 4
    Do you actually need regular expressions? Seems more like a case for standard string operations in whatever language you use. Commented Mar 17, 2016 at 20:41
  • 1
    Welcome to So ! I suggest you learn about regex from regular-expressions.info. Also mention in which programming language you are doing this. At last post your code or attempt in solving this question. Commented Mar 17, 2016 at 20:42
  • Yo do not need regex, you can just say something like final_str=str[0:9]+str[18:22]+str[22:-1] Commented Mar 17, 2016 at 20:47

1 Answer 1

1

First of all, this seems more appropiate for substring functions, they are usually faster and not so error-prone. However, for a learning purpose, you could come up with sth. like:

(.{9}).{8}(.{4}).

This matches any (not only digits, that is - for digits use \d instead) character 9 times, saves it in a group, matches another 8 characters which will not be saved, and will finally match another 4 characters into the second group.
Concenate $1 and $2 (5490028400000 in your case) and you should be fine.
See this demo on regex101.com.

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

2 Comments

Thanks for the feedback and suggestions. The language I'm using is C++, so I'm not sure if the above/below suggestions will work. Thanks for the "regular-expressions.info" link, I will definitely give this a look as well.
I'm making a little progress on this, and I'm using "(^\d{9})" to capture the first 9 characters in my string. Now, I just need to find a way to capture characters 18-21. The software that I'm using,only allows me to enter in a regular expression, I'm not allowed to concatenate using $1 or $2. Therefore, is there a simple expression I can add to mine, that grabs whichever numbers are in position 18-21?

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.