I need to check if a string variable contains three underscores "_". Fewer or higher amount of underscore should be false. How do I do that?
Asked
Active
Viewed 1,857 times
-2
-
1Why regex? Regular expressions are fantastic for doing a number of things, but this type of character counting can be done simpler with other tools. What language are you using? – Jason K Lai Dec 12 '19 at 16:35
-
1Just split by `_` and check count of array elements to be `4` – anubhava Dec 12 '19 at 16:37
-
`^(?:[^_]*_){3}[^_]*$` – ctwheels Dec 12 '19 at 16:40
-
1Does this answer your question? [Count the number of occurrences of a character in a string in Javascript](https://stackoverflow.com/questions/881085/count-the-number-of-occurrences-of-a-character-in-a-string-in-javascript). In PHP use `substr_count` (please always mention what environment you're working with and what you have tried and didn't work). – bobble bubble Dec 12 '19 at 16:50
-
Thanks all for the answers. For the ones saying "why use Regex?" - First of all, that was, obviously, not the question. Client wants to use Regex, otherwise I could easily have solved it with array-operations. But that's not the point. – Arte2 Dec 13 '19 at 12:31
1 Answers
1
^(?:[^_\n]*_){3}[^_\n]*$
should do the trick - Demo
This regex is inspired by ctwheels' comment, with the added change that newlines are included in the negated capture group to ensure that this regex does not match across multiple lines.
^(?:[^_\n]*_){3}
Starting from the beginning of the string, match any characters that aren't newline or underscore, then one underscore - and repeat this three times.[^_\n]*$
match non-underscore or newline characters to the end of the string.

Nick Reed
- 4,989
- 4
- 17
- 37