O
O
OwerFan2020-03-04 17:22:34
Regular Expressions
OwerFan, 2020-03-04 17:22:34

Don't understand regularity?

I have a question. According to regular expressions
, this search rule /\[(.+?)\]/ what should it do?
I argue like this. Find me what is enclosed in square brackets, it can be any character, from one to infinity. Symbol? say that it should be from 0 to 1. I do not understand. There is also grouping

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Pankov, 2020-03-04
@OwerFan

This regular expression will match text that starts with an opening square bracket and consists of one or more of any characters up to the nearest closing bracket.
The question is needed so that the plus sign is not greedy, that is, it does not gobble up the closing bracket either. By default, + and * are greedy, that is, they will gobble up as many characters as possible, but in order for the whole expression to match.
If your text "12[34]56[78]90"is , then a greedy regular expression (without a question) will find "[34]56[78]", and not a greedy one will find "[34]"and"[78]".

F
FanatPHP, 2020-03-04
@FanatPHP

The question mark in this case is the greed quantifier.

V
Vadim Priluzkiy, 2020-03-04
@Oxyd

Everything is simple. We go to regex101 , enter the regular expression, read the description on the right, enter the test lines below for verification.
Overall. Character by character: Looking for a single character [ -- \[ . Then we have a group in brackets (.+?) . -- any characters (except newline), +? -- repeated one or an unlimited number of times. And finally, look for the closing square bracket ] -- \] . As a result, this regular expression searches for a string of any length in square brackets.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question