Search code examples
c++regex

Matching a fixed position in a string using C++ regex


Do C++ regular expressions have a way to refer to a fixed position within a string? I am looking for a notation that is (fictitiously) shown in the following example as @n, where n is the index of the next character:

string = "hello12345";
re = "([a-z]+[0-9]+)(@7)(.+)";
// Match: ["hello12","345"]

Update: I cannot just repeat a fixed number of characters because I do not know how many of them will match [a-z] and [0-9].


Solution

  • Don't do it all with a regular expression. Use std::string::substr() to split the input into two substrings, the first 7 characters and the rest. Then check that the first substring matches the regexp ^[a-z]+\d+$.