Do not understand a regular expression using default grammar

The regular expression is:


 
auto pattern{ R"(^\s*(?!#)(\w+)\s*=\s*([\w\d]+)$)"s };


The part I do not understand is the group (?!#) - it is supposed to ignore lines beginning with # - but how? What's so special about "?!"

To complete the example here is the rest of the code for you to run:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <regex>
#include <string>
using namespace std::string_literals;

void usingRegExpressionsForParsingAString()
{
	auto text{ R"(
		#remove # to uncomment the following lines
		timeout=120
		server = 127.0.0.1
	)"s};

	auto pattern{ R"(^\s*(?!#)(\w+)\s*=\s*([\w\d]+)$)"s };

	auto rx = std::regex{ pattern };

	auto match = std::smatch{};

	auto end = std::sregex_iterator{};
	for ( auto it = std::sregex_iterator { std::begin(text), std::end(text), rx};
		it != end; ++it)
	{
		std::cout << "'" << (*it)[1] << "'='" << (*it)[2] << "'" << std::endl;
	}
}


If I remove the ! std::regex creation throws an exception; if I remove the ? it does not throw but no matches are found.

I tested it with another character and it does seem that (?!x) makes it impossible to match x character (for any character with no special meaning in the regular expression syntax...

So, what is the meaning of (?!#)?


Regards,
Juan
no need, may be dropped
as long as anchor, \s , \w class set, are in a row
as \w set impossible being a # char
Last edited on
https://regex101.com/
Enter the regex, and it will show you a detailed explanation.
Enter some text, and it will show you what matches (or doesn't).
@salem c, thanks for the link. regex searches have always looked rather arcane and mysterious, though admittedly I have not had any urgent need to bother learning it.
Topic archived. No new replies allowed.