Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make std::regex begin matching at a specific position in a string?

Tags:

c++

regex

c++11

C#'s Regex.Match method has an overload that allows the matching to begin at a specific offset.

How can I make std::regex begin matching at a specified position in the string?

Note regarding the naive solution:

No, I cannot just pass a substring starting at that position -- the prefix might change things.

For example, the prefix may indicate that the given position is not the beginning of a new line, whereas if I chopped off the string, it would appear like a new line and I would get an incorrect match for patterns that need to detect newlines. The same problem exists for lookbehinds and such.

like image 310
user541686 Avatar asked Oct 05 '22 10:10

user541686


1 Answers

The key is that you would want to use the match flag to specify that the iterator is part of a larger string.

You would need to use an iterator that has been advanced as @ildjarn suggested, and then use the flag std::regex_constants::match_prev_avail which specifies that the iterator --first is dereferencable. This will allow the regular expression matcher to use the immediately previous element as part of its testing.

like image 124
Dave S Avatar answered Oct 12 '22 00:10

Dave S