Regex Question Mark

To match a string to a pattern, for example:

-TEXT-someMore-String 

To get -TEXT- , I found out that this works:

 /-(.+?)-/ // -TEXT- 

How do i know ? makes the previous token as optional, as in:

colou?r matches both colour and color

I first put in regex to get the -TEXT- part as follows:

 /-(.+)-/ 

But he gave -TEXT-someMore- .

How to add ? stops the regular expression to get the -TEXT- part correctly? Since he used to make the previous token optional, without stopping at a certain point, as in the example above?

+3
source share
4 answers

How do you say ? sometimes means zero or one, but in your regular expression +? there is a single element meaning "one or more" and preferably as little as possible. "(This contrasts with bare + , which means" one or more "and preferably as much as possible.")

As the documentation :

However, if the quantifier is followed by a question mark, then it becomes lazy and instead corresponds to a minimum number of times, therefore the template /\*.*?\*/ does the right thing with comments C. Meaning different quantifiers do not change otherwise, only the preferred number of matches . Do not confuse this use with a question mark with its use as a quantifier in your own right. Since it has two uses, it can sometimes be doubled, because in \d??\d , which matches one digit by preference, but can match two if this is the only way to match the rest of the pattern.

+9
source

Alternatively, you can use the U ngreedy modifier to set the search for the shortest match for the entire regular expression:

 /-(.+)-/U 
+3
source

? before the token is abbreviated for {0,1}, which means: everything from 0 to 1 appears as the main one.

But + not a token, but a quantifier. abbreviation for {1,}: 1 to endless appearances.

A? after the quantifier sets it to non-separation mode. If in greedy mode it matches the maximum possible line. If not greedy, he will be as small as possible

+2
source

Another, possibly the main mistake in your regex is that you try to match multiple arbitrary characters with .+? . However, you really want to probably: "any character except -". You can get this via [^-]+ . In this case, it doesn’t matter if you make a greedy match or not - the second match will end as soon as you encounter the second β€œ-” in your line.

+1
source

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


All Articles