-1

I currently using regex.h for a c program

wanted to ensure a string starts and ends with the @ which surrounds alphanumeric chars, (only 2 @'s none in the middle)

UPDATE: I think i fixed the first question by using the ^ and $ anchor tags. If that doesn't look like the right way to fix the problem please let me know.

my code right now:

(regexCheck(tag, "^[@]+[A-Za-z0-9]+[@]$") == 1)

additionally i wanted to make sure a string contained an _ with alphanumeric chars (eg. _test , te_st, test_ are all valid, but test is not valid)

my code right now:

(regexCheck(string, "[A-Za-z0-9_]")) == 1

Any help would be appreciated, but an explanation with regex grammar would also be appreciated.

  • I can never remember the differences between the different regex flavors, but did you try `^@[a-zA-z0-9]+_[a-zA-Z0-9]+$`? – nemequ Jan 21 '18 at 02:06
  • 1
    How many alphas need to be in the middle? Is `@_@` a valid string? – Tim Biegeleisen Jan 21 '18 at 02:17
  • yes @_@ is a valid string... but i think i fixed the first problem of the @ symbols with (regexCheck(tag, "^[@]+[A-Za-z0-9]+[@]$") == 1) – Andre D'Souza Jan 21 '18 at 02:19
  • 1
    Please ask only one question per question. If there is some general concept which confuses you (like "how do I make sure a regex matches an entire string?"), that makes for a better question. – rici Jan 21 '18 at 07:52
  • The first regex looks like it will unwantedly match `@@a@` and `@ab@` and will unwantely not match `@a_b@`.If I understood your goal correctly you want to fix all of that, right? I have a solution which would fix them, it would however also match `@_@`, is that ok? Your question could also be read like requiring anywhere between the @ at least one alphanumeric. I.e. it should match `@a_@` and `@_b@` but not `@_@`. Is that needed? – Yunnosch Jan 21 '18 at 08:40
  • Try `^@[A-Za-z0-9]*_[A-Za-z0-9]*@$` – Wiktor Stribiżew Jan 21 '18 at 14:17
  • Did my answer work for you? – Wiktor Stribiżew Sep 14 '20 at 10:48

1 Answers1

0

You may use

^@[A-Za-z0-9]*_[A-Za-z0-9]*@$

See the regex demo. Note that you should specify the REG_EXTENDED flag when compiling the regex pattern so that $ could be parsed correctly as the end of string anchor.

Pattern details

  • ^ - start of string
  • @ - a @ char
  • [A-Za-z0-9]* - 0 or more ASCII letters, digits
  • _ - an underscore
  • [A-Za-z0-9]* - 0 or more ASCII letters, digits
  • @ - a @ char
  • $ - end of string anchor.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • This requires, and allows, a single underscore. Maybe the OP also needs to see how to allow repeated underscores? `^@[A-Za-z0-9](_[A-Za-z0-9]*)+$` – tripleee Jan 21 '18 at 19:33