1

like strings lines below, i want to match the the string which must have 1 number and letter(short commit id).

online-release-0202-c3764ab8-02022329     #i need c3764ab8  
online-release-0202-02022329-c3764ab8     #i need c3764ab8

I tried the following rules, but it always matches a string of pure numbers

(?=([a-f0-9]{8}))
mk_
  • 409
  • 1
  • 3
  • 17
  • Your requireqments are not clear. Your sample `c3764ab8` has 5 numbers and 3 letters. – jhnc Apr 16 '21 at 04:10

2 Answers2

2

Assuming the commit id must has at least one digit and one letter a-f

Try this regex:

(?!\d{8}|[a-f]{8})[a-f\d]{8}
  • (?!\d{8}|[a-f]{8}) negative lookahead, the following 8 characters are not formed only by digits or letters a-f
  • [a-f\d]{8} match 8 characters that are digits and a-f

Check the proof


If you're checking a git commit id, this rule doesn't always apply. It's an SHA hash that can be formed with pure numbers or a-f. Thus 02022329 is also a legal git commit id.

It is better to make your naming convention consistent to eliminate ambiguity.

Hao Wu
  • 17,573
  • 6
  • 28
  • 60
1

You might also assert a char a-f and a digit using a positive lookahead (?= and then match 8 times either one of them using word boundaries \b to prevent a partial match.

\b(?=[0-9]*[a-f])(?=[a-f]*[0-9])[a-f0-9]{8}\b

The pattern matches:

  • \b A word boundary to prevent a partial match
  • (?=[0-9]*[a-f]) Positive lookahead, assert a char a-f
  • (?=[a-f]*[0-9]) Positive lookahead, assert a digit 0-9
  • [a-f0-9]{8} Match 8 times either a char a-f or a digit 0-9
  • \b A word boundary

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70