code kid
code kid

Reputation: 414

optionals in a look around regular expressions

I'm trying to figure out how to put option values in a lookaround with regular expressions.

These values should match

3
1000
15-20
2048-4096/100

This value should not

3/4

I want to say in regex "only match if there is a dash 4 digit number and a colon preceding the / division symbol

For example:

  1. -9999 preceding the / division symbol should match
  2. 9999/ should not match because there is no -
  3. -/ should not match because there is no number

    ^[^0][0-9]*(-|:)?([0-9]*)?(?<=[0-9])(\/)?([0-9]*)$

I have the look around just looking for a preceding number but if I put a ? or * in it it no longer works. Thanks for the help!!!

Upvotes: 0

Views: 42

Answers (1)

noahnu
noahnu

Reputation: 3574

^\d+(?:[-:](?:\d{4}\/\d+|\d+))?$

If I'm understanding what you want correctly,

  • \d+ Starts with some number
  • (?: ...)? Followed by optional pattern which begins with a dash or colon
  • \d{4}/\d+ The number in the optional group can be a 4 digit number with a slash and another number
  • \d+ Or the optional group can be any number if it doesn't begin with a slash.

Upvotes: 2

Related Questions