yugosonegi
yugosonegi

Reputation: 65

Match regex on the end but ignore a few parts if exists

Imagine that I have this delimiter that is on the end of the string: -holyday[part1], I want to match only the -holyday and ignore if exists [part1]. A complete string example: with my family - holyday[part1].

This is what I have right now but I can only make it match with the [part1]:

\-\s?([\w\[\]]+)$

Upvotes: 1

Views: 1032

Answers (2)

The fourth bird
The fourth bird

Reputation: 163457

You could use a positive lookahead to assert that your content begins with a - and what follows is [part1] Maybe this is what you are looking for:

-\s[\w\s]+(?=\[\w+\])

Explanation

  • Match a dash -
  • Match a whitespace \s
  • Match a word character or a white space one or more times [\w\s]+
  • A positive lookahead (?=
  • That asserts that what follows is one or more word character between brackets \[\w+\]
  • Close the lookahead )

If the pattern for - and [text] occurs multiple times and you want only the last occurence, you could for example add another negative lookahead (?!.*\[.*\])to assert that no more patterns like [text] follow. (text like part1)

-\s[\w\s]+(?=\[\w+\](?!.*\[.*\]))

Upvotes: 0

CaHa
CaHa

Reputation: 1166

(?:...) is a non-capturing group

(\-\s?\w+)(?:\[part1\])$ does what you want (example 1)

and this regex removes everything after [ (inclusive):

(\-[^\[]+).* (example 2)

Upvotes: 1

Related Questions