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(®ex, "^#[[: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(®ex, "^#[_[:alnum:]][:alnum:]{0,97}#", 0);
Related
I'd like to match all strings that begin with a set of characters a-z, then exactly one : and another set of characters a-z right after that.
So as an example, the string "an:example" would be a correct match.
And another example, "another:ex:ample" needs to be a mismatch.
I have tried to set it up like that but it matches everything, even if i take bad string as input :(
So my regular expression is "[a-z]:[a-z]" but it evaluates the string "1an:example" as a Match :/
How can I do this correctly?
#include <stdio.h>
#include <regex.h>
int main() {
regex_t regex;
int retis;
char* str = "1an:example";
retis = regcomp(®ex, "[a-z]:[a-z]", 0);
retis = regexec(®ex, str, 0, NULL, 0);
if(!retis) {
puts("Match");
}
else if(retis == REG_NOMATCH) {
puts("No match");
}
regfree(®ex);
return 0;
}
You need
retis = regcomp(®ex, "^[a-z]+:[a-z]+$", REG_EXTENDED);
See the C online demo.
That is:
^ (start of string) and $ (end of string) are anchors that require the regex to match the whole string
[a-z]+ matches one or more lowercase letters
REG_EXTENDED allows extended regex syntax, e.g. in regex.h it is required to enable the $ anchor.
I'd like to match all strings that begin with a set of characters a-z, then exactly one : and another set of characters a-z right after that.
So as an example, the string "an:example" would be a correct match.
And another example, "another:ex:ample" needs to be a mismatch.
I have tried to set it up like that but it matches everything, even if i take bad string as input :(
So my regular expression is "[a-z]:[a-z]" but it evaluates the string "1an:example" as a Match :/
How can I do this correctly?
#include <stdio.h>
#include <regex.h>
int main() {
regex_t regex;
int retis;
char* str = "1an:example";
retis = regcomp(®ex, "[a-z]:[a-z]", 0);
retis = regexec(®ex, str, 0, NULL, 0);
if(!retis) {
puts("Match");
}
else if(retis == REG_NOMATCH) {
puts("No match");
}
regfree(®ex);
return 0;
}
You need
retis = regcomp(®ex, "^[a-z]+:[a-z]+$", REG_EXTENDED);
See the C online demo.
That is:
^ (start of string) and $ (end of string) are anchors that require the regex to match the whole string
[a-z]+ matches one or more lowercase letters
REG_EXTENDED allows extended regex syntax, e.g. in regex.h it is required to enable the $ anchor.
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(®ex, "^/.{3}[0-9]", 0);
// here checking compilation result - is OK (it means: equal 0)
/* Execute regular expression */
reti = regexec(®ex, "/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(®ex, "^/.{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).
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(®ex, "\\\"access_token\\\".\\\"(.*?)\\\"", 0);
regmatch_t pmatch[1];
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
reti = regexec(®ex, client_credentials, 1, pmatch, 0);
if (!reti) {
puts("Match");
} else if (reti == REG_NOMATCH) {
puts("No match");
} else {
regerror(reti, ®ex, 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(®ex, "\\\"access_token\\\".\\\"(.*?)\\\"", 0);
^
That should be:
reti = regcomp(®ex, "\\\"access_token\\\": \\\"(.*?)\\\"", 0);
Then we don't need to escape quotes in regexes. That makes it easier to read.
reti = regcomp(®ex, "\"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(®ex, "\"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(®ex, "\"access_token\".\"([^)]*)\"", 0);
...
reti = regexec(®ex, 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).
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(®ex, "[+-]?([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(®ex, 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.