Match Regular Expressoin, if the string contains exactly N random characters

I would like the regular expression to match the string only if it contains a character that has a predefined number of times.

For example: I want to match all lines containing the character "_" 3 times;

So, โ€œa_b_c_dโ€ will go through โ€œa_bโ€ will fail
"a_b_c_d_e" will fail

Does anyone know a simple regex that will satisfy this?

thanks

+4
source share
4 answers

As an example, you can:

\b[az]*(_[az]*){3}[az]*\b 

(with flag of ignore flag).

You can play with him here

It says "a match of 0 or more letters, followed by" _ [az] * "exactly three times, followed by 0 or more letters." \b means "word boundary", i.e. "Match the whole word."

Since I used '*', this will correspond if there are exactly three words โ€œ_โ€ in the word, regardless of whether it appears at the beginning or end of the word - you can change it otherwise.

In addition, I suggested that you want to combine all the words in the line with exactly three "_" in it.

This means that the string "a_b a_b_c_d" will say that "a_b_c_d" is transmitted (but "a_b" does not work).

If you mean that globally throughout the line you only need three "_s", use:

 ^[^_]*(_[^_]*){3}[^_]*$ 

This binds the regular expression at the beginning of the line and comes to an end, making sure that it contains only three occurrences of "_".

+5
source

This should do it:

 ^[^_]*_[^_]*_[^_]*_[^_]*$ 
+1
source

Developing Rado's answer, which so far is the most multivalent, but it can be painful to write if there are more matches:

 ^([^_]*_){3}[^_]*$ 

It will correspond to entire lines (from start ^ to end $ ), in which there is exactly 3 ( {3} ) times a pattern consisting of 0 or more ( * ), for any character, ( [^_] ) and one underscore ( _ ), followed by 0 more times than any character except the underscore ( [^_]* , again).

Of course, an alternative could be grouped the other way around, since in our case the pattern is symmetrical:

 ^[^_]*(_[^_]*){3}$ 
+1
source

If you are examples, these are the only possibilities (for example, a_b_c _...), then the rest is all right, but I wrote one that will handle some other possibilities. For instance:

 a__b_adf a_b_asfdasdfasfdasdfasf_asdfasfd ___ _a_b_b 

Etc.

Here is my regex.

 \b(_[^_]*|[^_]*_|_){3}\b 
0
source

Source: https://habr.com/ru/post/1396756/


All Articles