简体   繁体   中英

Regular expression match 0 or exact number of characters

I want to match an input string in JavaScript with 0 or 2 consecutive dashes, not 1, ie not range.

If the string is:

  • -g:"apple" AND --projectName:"grape" : it should match --projectName:"grape" .
  • -g:"apple" AND projectName:"grape" : it should match projectName:"grape" .
  • -g:"apple" AND -projectName:"grape" : it should not match, ie return null.
  • --projectName:"grape" : it should match --projectName:"grape" .
  • projectName:"grape" : it should match projectName:"grape" .
  • -projectName:"grape" : it should not match, ie return null.

To simplify this question considering this example, the RE should match the preceding 0 or 2 dashes and whatever comes next. I will figure out the rest. The question still comes down to matching 0 or 2 dashes.

  1. Using -{0,2} matches 0, 1, 2 dashes.
  2. Using -{2,} matches 2 or more dashes.
  3. Using -{2} matches only 2 dashes.

How to match 0 or 2 occurrences?

Answer

If you split your "word-like" patterns on spaces, you can use this regex and your wanted value will be in the first capturing group:

(?:^|\s)((?:--)?[^\s-]+)
  • \\s is any whitespace character (tab, whitespace, newline...)
  • [^\\s-] is anything except a whitespace-like character or a -

Once again the problem is anchoring the regex so that the relevant part isn't completely optionnal: here the anchor ^ or a mandatory whitespace \\s plays this role.


What we want to do

Basically you want to check if your expression (two dashes) is there or not, so you can use the ? operator:

(?:--)?

"Either two or none", (?:...) is a non capturing group.

Avoiding confusion

You want to match "zero or two dashes", so if this is your entire regex it will always find a match: in an empty string, in -- , in - , in foobar ... What will be match in these string will be an empty string, but the regex will return a match.

This is a common source of misunderstanding, so bear in mind the rule that if everything in your regex is optional, it will always find a match.

If you want to only return a match if your entire string is made of zero or two dashes, you need to anchor the regex:

^(?:--)?$

^$ match respectively the beginning and end of the string.

a(-{2})?(?!-)

This is using "a" as an example. This will match a followed by an optional 2 dashes.

Edit:

According to your example, this should work

(?<!-)(-{2})?projectName:"[a-zA-Z]*"

Edit 2: I think Javascript has problems with lookbehinds.

Try this:

[^-](-{2})?projectName:"[a-zA-Z]*"

正则表达式可视化

Debuggex Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM