Regex to exclude text between first occurrence of underline and last occurrence of hyphon

Viewed 65

I am searching for a regex to match

  1. the text until (and including) the first occurrence of an underline and
  2. the text after the last occurrence of a hyphon, but cutting all leading zeros

Sample input:

Text_un_important-0011

Desired result (by concatenting all matches):

Text_11

I have come up with: (?:^|(?:00))(.+?)(?:$|_) but it has some flaws: It works only if there is exactly one hyphen at the end and two leading zeros. Unfortunately I cannot fix it.

2 Answers

If you follow your current logic, you may use

^[^_]*_|[1-9]\d*$

See the regex demo. Details:

  • ^ - start of string
  • [^_]* - 0 or more chars other than _ and then
  • _ - a _ char
  • | - or
  • [1-9] - a non-zero digit
  • \d* - 0 or more digits
  • $ - end of string

You may also use a replace logic:

Find:       _.*-0*
Replace: _

See the regex demo. The _.*-0* pattern matches

  • _ - an underscore
  • .* - any 0 or more chars other than line break chars, as many as possible
  • - - a hyphen
  • 0* - zero or more 0 chars.

Since the first _ is consumed, the replacement pattern should be _.

So , you want to capture the first word and the final digits that are not zero:

([\w\d]+)(_[\w\d]+)*(-0*)(\d+)

use the first and last captured group.

  • ([\w\d]+) captures a word that may have a number (ex. word1)
  • (_[\w\d]+)* captures repetitions of _word (ex. _word1_anotherword2_third3)
  • (-0*) captures a hyphen followed by consecutive zeros (ex. -00000000)
  • (\d+) captures all the digits following the consecutive zeros
Related