0

The regex pattern is :

enter image description here

However its not a valid pattern as the syntax is wrong (there should be a . preceding * in 2 places)

Correct pattern is :

enter image description here

Is there a way to validate the syntax of these regex patterns in C programming? Any library or function which would evaluate the above wrong pattern and return invalid pattern? I tried using regcomp (but it did not return invalid pattern for the wrong input)

James Z
  • 12,104
  • 10
  • 27
  • 43
Person
  • 1
  • 3

3 Answers3

0

You might want to go overboard and do it in C with a library, or check out these live testing tools https://regex101.com/ or https://www.debuggex.com/

Gunther Schulz
  • 575
  • 3
  • 18
0

There are regex libraries for c you can use (see Regular expressions in C: examples? ). When you want to find out, if a given string has valid regex format, you can do this by using another regex ( see Is there a regular expression to detect a valid regular expression?), or you can try to "compile" the string as regex. I think the first way is the cleaner way.

jjj
  • 555
  • 1
  • 3
  • 16
0

It depends on the regex implementation you're using. Here's an example using POSIX extended regular expressions that simply checks the return value of regcomp and prints an error message obtained with regerror:

#include <regex.h>
#include <stdio.h>
#include <string.h>

void test(const char *regex) {
	regex_t preg;
	int errcode = regcomp(&preg, regex, REG_EXTENDED);
	if (errcode == 0) {
		printf("%s => Success\n", regex);
		regfree(&preg);
	}
	else {
		char errmsg[80];
		regerror(errcode, NULL, errmsg, 80);
		printf("%s => %s\n", regex, errmsg);
	}
}

int main() {
	test("(*\\.com)");
	test("(.*\\.com)");
	return 0;
}

Try it online!

This should print something like:

(*\.com) => Invalid preceding regular expression
(.*\.com) => Success

Note that (*\.com) is a valid POSIX basic regex since an unescaped ( matches a literal (. With basic regexes, a * at the beginning of a regex or parenthesized subexpression also matches a literal *.

nwellnhof
  • 30,198
  • 7
  • 82
  • 110
  • With the same code, if we try the above pattern(what i have mentioned in the question) , it fails to throw error, rather compiles successfully (no . before *) – Person Feb 01 '19 at 16:15