0

I've already read this here and I still have got some questions. I will be very grateful if you can help me to solve them. I'm trying to compose a RegEx to verify that a string contains only letters, numbers, underscores and hyphens. Firstly, when I tried to do it (without Google-search) I did this @"[A-Za-z0-9_-]". After I made some research I found that it should be @"^[a-zA-Z0-9_-]$" where:

^ asserts position at start of a line
$ asserts position at the end of a line

My question is why we should insert these symbols?regex101.com And my other question is why the string "jeffbutt" (with yellow in the screenshot) doesn't match?

Kaloyan K.
  • 309
  • 1
  • 7
  • You have no quantifier, so it is only expecting one char. Add an * behind your character class: `^[a-zA-Z0-9_-]*$` – Christoph Herold Apr 02 '19 at 21:28
  • @ChristophHerold There is `*`, the formatting is wrong. – Wiktor Stribiżew Apr 02 '19 at 21:29
  • Your string DOES match, just not in combination with the other strings. If you only put in `jeffbutt`, the match works fine. In your example, you are trying to match a string with commas, spaces, etc. Of course, it's not going to match. And to explain `^` and `$`: If they are not present, the regex will match any occurence in the string, it does not necessarily have to be the whole string. – Christoph Herold Apr 02 '19 at 21:31
  • @WiktorStribiżew, I said that I've read most of the posts with my problem and I still can't got it and you marked my theme as duplicate. :( – Kaloyan K. Apr 02 '19 at 21:32
  • There is no problem with your regex. [`^` and `$`](https://stackoverflow.com/questions/6908725/what-do-and-mean-in-a-regular-expression) are there to match start/end of string. And that is exactly why `jeffbutt` can't match. – Wiktor Stribiżew Apr 02 '19 at 21:35
  • Your problem is that your match the start and the end of string and do not include whitespace in the pattern. That's why string 'jeffbutt' matches, but your whole sentence does not. –  Apr 02 '19 at 21:36
  • 1
    Example without `^` and `$`: If you put in `inv@lid`, it will be able to match `inv`, so that fits. If you put in ONLY the `^`, it will still be able to match it, since it occurs at the start of the string. If, on the other hand, you only included `$`, it would be able to match `lid`, because it is at the end of the string. Only with both in place will the string have to be composed ONLY of the allowed characters. – Christoph Herold Apr 02 '19 at 21:36
  • 1
    And since `^` and `$` typically match at the start and end of a line, you could write your example as multiple lines: https://regex101.com/r/qAZ0RS/1. Here, you can see, that only `!nv@lid ch@rs` fails to match. The other lines consist only of allowed characters. – Christoph Herold Apr 02 '19 at 21:40
  • @ChristophHerold, thank you! – Kaloyan K. Apr 02 '19 at 21:43
  • I will try to find some more examples and I think I'll fully understand it. – Kaloyan K. Apr 02 '19 at 21:44

0 Answers0