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.
-
4Do you actually need regular expressions? Seems more like a case for standard string operations in whatever language you use.Sebastian Proske– Sebastian Proske2016-03-17 20:41:49 +00:00Commented Mar 17, 2016 at 20:41
-
1Welcome 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.user2705585– user27055852016-03-17 20:42:08 +00:00Commented 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]pregmatch– pregmatch2016-03-17 20:47:05 +00:00Commented Mar 17, 2016 at 20:47
Add a comment
|
1 Answer
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.
2 Comments
dbaalke
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.
dbaalke
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?