C: Regular Expression does not match floating point literals - c

I'm writing a simple script to match floating points literals, only +123.23, -123.23 or 123.23 etc should be matched, so I don't match those -1.0e-10 form. So my expression is as simple as: [+-]?([0-9]*[.])?[0-9]+ which will capture the sign, digits, dot and fraction for me optionally. And my C validation looks like:
reti = regcomp(&regex, "[+-]?([0-9]*[.])?[0-9]+", 0);
if (reti) {
fprintf(stderr, "Could not compile regex of floating literals\n");
exit(1);
}
char * testString = "-87.21";
reti = regexec(&regex, testString, 0, NULL, 0);
if (!reti) {
printf("%s \n", testString);
}
However, the value of reti is 1, which means my regex on test string "-87.21" failed. I tested my regex on regexr.com, it matches "-87.21", So I don't really know what happens here. Is there anyone can help?

You need to add the REG_EXTENDED flag when calling regcomp or else adapt your regex to be compatible with POSIX BRE (Basic Regular Expressions, the legacy syntax used by sed and grep without -E). BRE is the default and probably not what you want.

Related

Matching forward slash in regex

I've troubles with preparing regex expression, matching forward slash ('/') inside.
I need to match string like "/ABC6" (forward slash, then any 3 characters, then exactly one digit). I tried expressions like "^/.{3}[0-9]", "^\/.{3}[0-9]", "^\\/.{3}[0-9]", "^\\\\/.{3}[0-9]" - without success.
How should I do this?
My code:
#include <regex.h>
regex_t regex;
int reti;
/* Compile regular expression */
reti = regcomp(&regex, "^/.{3}[0-9]", 0);
// here checking compilation result - is OK (it means: equal 0)
/* Execute regular expression */
reti = regexec(&regex, "/ABC5", 0, NULL, 0);
// reti indicates no match!
NOTE: this is about C language (gcc) on linux (Debian). And of course the expression like "^\/.{3}[0-9]" causes gcc compilation warning (unknown escape sequence).
SOLUTION: as #tripleee suggested in his answer, the problem was not caused by slash, but by brackets: '{' and '}', not allowed in BRE, but allowed in ERE. Finally I changed one line, then all works OK.
reti = regcomp(&regex, "^/.{3}[0-9]", REG_EXTENDED);
The slash is fine, the problem is that {3} is extended regular expression (ERE) syntax -- you need to pass REG_EXTENDED or use \{3\} instead (where of course in a C string those backslashes need to be doubled).

In C, How to get capturing group RegEx?

This is the C function I am having problems with:
char get_access_token(char *client_credentials)
{
regex_t regex;
int reti;
char msgbuf[100];
reti = regcomp(&regex, "\\\"access_token\\\".\\\"(.*?)\\\"", 0);
regmatch_t pmatch[1];
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
reti = regexec(&regex, client_credentials, 1, pmatch, 0);
if (!reti) {
puts("Match");
} else if (reti == REG_NOMATCH) {
puts("No match");
} else {
regerror(reti, &regex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
return (char) "";
}
The string that I'm trying to parse is a JSON string, I don't care about the actual structure I only care about the access token.
It should look like this:
{"access_token": "blablablabal"}
I want my function to return just "blablablabla"
The RegEx that I'm trying to use is this one:
\"access_token"."(.*?)"
but I can't find that in the variable pmatch, I only find two numbers in that array, I don't really know what those numbers mean.
What am I doing wrong?
P.S. I'm a C noob, I'm just learning.
There's several problems. You have typos in your regex. And you're trying to use extended regex features with a POSIX regex.
First the typos.
reti = regcomp(&regex, "\\\"access_token\\\".\\\"(.*?)\\\"", 0);
^
That should be:
reti = regcomp(&regex, "\\\"access_token\\\": \\\"(.*?)\\\"", 0);
Then we don't need to escape quotes in regexes. That makes it easier to read.
reti = regcomp(&regex, "\"access_token\": \"(.*?)\"", 0);
This still doesn't work because it's using features that basic POSIX regexes do not have. Capture groups must be escaped in a basic POSIX regex. This can be fixed by using REG_EXTENDED. The *? non-greedy operators is an enhanced non-POSIX feature borrowed from Perl. You get them with REG_ENHANCED.
reti = regcomp(&regex, "\"access_token\": \"(.*?)\"", REG_ENHANCED|REG_EXTENDED);
But don't try to parse JSON with a regex for all the same reasons we don't parse HTML with a regex. Use a JSON library such as json-glib.
Well, your pmatch array must have at least two elements, as you probably know, group 0 is the whole matching regexp, and it is filled for the whole regexp (like if all the regular expression were rounded by a pair of parenthesis) you want group 1, so pmatch[1] will be filled with the information of the first subexpression group.
If you look in the doc, the pmatch element has two fields that index the beginning index in the original buffer where the group was matched, and the one past the last index of the place in the string where the group ends. These field names are rm_so and rm_eo, and like the ones in pmatch[0], they indicate the index at where the regular (sub)expression begins and ends, resp.
You can print the matched elements with (once you know that they are valid, see doc) with:
#define SIZEOF(arr) (sizeof arr / sizeof arr[0])
...
regmatch_t pmatch[2]; /* for global regexp and group 1 */
...
/* you don't need to escape " chars, they are not special for regcomp,
* they do, however, for C, so only one \ must be used. */
res = regcomp(&regex, "\"access_token\".\"([^)]*)\"", 0);
...
reti = regexec(&regex, client_credentials, SIZEOF(pmatch), pmatch, 0);
for (i = 0; i < regex.re_nsub; i++) {
char *p = client_credentials + pmatch[i].rm_so; /* p points to beginning of match */
size_t l = pmatch[i].rm_eo - pmatch[i].rm_so; /* match length */
printf("Group #%d: %0.*s\n", i, l, p);
}
My apologies for submitting a snippet of code instead of a verifiable and complete example, but as you didn't do it in the question (so we could not test your sample code) I won't do in the answer. So, the code is not tested, and can have errors on my side. Beware of this.
Testing a sample response requires time, worse if we have first to make your sample code testable at all. (this is a complaint about the beginners ---and some nonbeginners--- use of not posting Minimal, Complete, and Verifiable example).

Regex in C For Matching

I need to make a regex that can match any alphanumeric string of a length < 99 enclosed by two #. The first character after the '#' can also be '_' which I'm not sure how to account for.
Ex. #U001# would be valid. #_A111# would also be valid. However, #____ABC# would not be valid, and neither would #ABC.
I'm relatively new to regex and noticed that the \z is an unrecognized escape sequence. I'm trying to write it in C11 if that matters.
#include <regex.h>
regex_t regex;
int reti;
char msgbuf[100];
/* Compile regular expression */
reti = regcomp(&regex, "^#[[:alnum:]]#\z", 0);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
Try using the following pattern:
^#[_[:alnum:]][:alnum:]{0,97}#
Here is a brief explanation of the pattern
^ from the start of the string
# match #
[_[:alnum:]] match underscore or alpha
[:alnum:]{0,97} then match zero to 97 alpha
# match #
Code:
reti = regcomp(&regex, "^#[_[:alnum:]][:alnum:]{0,97}#", 0);

usage of + in Posix Regex library

This should be pretty simple, but I am having trouble understanding the basic working of '+' in regex.h library in C. Not sure what is going wrong.
Pasting a sample code which doesn't work. I want to find a string which starts with B and ends with A, there can be more than one occurrence of B so I want to use B+
int main(int argc, const char * argv[])
{
regex_t regex;
int reti;
/* Compile regular expression */
reti = regcomp(&regex, "^B+A$", 0);
if( reti)
{
printf("Could not compile regex\n");
exit(1);
}
/* Execute regular expression */
reti = regexec(&regex, "BBBA", 0, NULL, 0);
if (!reti )
{
printf("Match\n");
}
else if( reti == REG_NOMATCH )
{
printf("No match\n");
}
else
{
printf("Regex match failed\n");
exit(1);
}
/* Free compiled regular expression if you want to use the regex_t again */
regfree(&regex);
return 0;
}
This does not find the match, but I am not able to understand why.
Usage of ^BB*A$ works fine, but that is not something I would want.
As I also want to check for something like ^[BCD]+A$ which should match BBBA or CCCCA or DDDDA. Usage of ^[BCD][BCD]*A$ wont work for me as that could match BCCCA which is not the desired match.
Tried using parentheses and brackets in the expression but it doesn't seem to help.
Quick help is much appreciated.
By default regcomp() compiles a pattern as a so-called Basic Regular Expression; in such regular expressions the + operator is not available. The regex syntax you're trying to use is known as Extended Regular Expression syntax. In order to have regcomp() work with that more extended syntax you need to pass it the REG_EXTENDED flag.
By the way, this comment:
As I also want to check for something like ^[BCD]+A$ which should match BBBA or CCCCA or
DDDDA. Usage of ^[BCD][BCD]*A$ wont work for me as that could match BCCCA which is not the
desired match
is based on a misconception of how the quantifiers + and * work. The regular expressions ^[BCD]+A$ and ^[BCD][BCD]*A$ are exactly equivalent.

Compiling/Matching POSIX Regular Expressions in C

I'm trying to match the following items in the string pcode:
u followed by a 1 or 2 digit number
phaseu
phasep
x (surrounded by non-word chars)
y (surrounded by non-word chars)
z (surrounded by non-word chars)
I've tried to implement a regex match using the POSIX regex functions (shown below), but have two problems:
The compiled pattern seems to have no subpatterns (i.e. compiled.n_sub == 0).
The pattern doesn't find matches in the string " u0", which it really should!
I'm confident that the regex string itself is working—in that it works in python and TextMate—my problem lies with the compilation, etc. in C. Any help with getting that working would be much appreciated.
Thanks in advance for your answers.
if(idata=tb_find(deftb,pdata)){
MESSAGE("Global variable!\n");
char pattern[80] = "((u[0-9]{1,2})|(phaseu)|(phasep)|[\\W]+([xyz])[\\W]+)";
MESSAGE("Pattern = \"%s\"\n",pattern);
regex_t compiled;
if(regcomp(&compiled, pattern, 0) == 0){
MESSAGE("Compiled regular expression \"%s\".\n", pattern);
}
int nsub = compiled.re_nsub;
MESSAGE("nsub = %d.\n",nsub);
regmatch_t matchptr[nsub];
int err;
if(err = regexec (&compiled, pcode, nsub, matchptr, 0)){
if(err == REG_NOMATCH){
MESSAGE("Regular expression did not match.\n");
}else if(err == REG_ESPACE){
MESSAGE("Ran out of memory.\n");
}
}
regfree(&compiled);
}
It seems you intend to use something resembling the "extended" POSIX regex syntax. POSIX defines two different regex syntaxes, a "basic" (read "obsolete") syntax and the "extended" syntax. To use the extended syntax, you need to add the REG_EXTENDED flag for regcomp:
...
if(regcomp(&compiled, pattern, REG_EXTENDED) == 0){
...
Without this flag, regcomp will use the "basic" regex syntax. There are some important differences, such as:
No support for the | operator
The brackets for submatches need to be escaped, \( and \)
It should be also noted that the POSIX extended regex syntax is not 1:1 compatible with Python's regex (don't know about TextMate). In particular, I'm afraid this part of your regexp does not work in POSIX, or at least is not portable:
[\\W]
The POSIX way to specify non-space characters is:
[^[:space:]]
Your whole regexp for POSIX should then look like this in C:
char *pattern = "((u[0-9]{1,2})|(phaseu)|(phasep)|[^[:space:]]+([xyz])[^[:space:]]+)";

Resources