esengineer
esengineer

Reputation: 9918

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, i.e. not range.

If the string is:

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?

Upvotes: 2

Views: 2767

Answers (2)

Robin
Robin

Reputation: 9644

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.

Upvotes: 4

Martyn
Martyn

Reputation: 806

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]*"

Regular expression visualization

Debuggex Demo

Upvotes: 2

Related Questions