You are viewing limited content. For full access, please sign in.

Question

Question

Pattern Matching Request

asked on November 18, 2019

Hoping one of you pattern matching experts can provide a bit of assistance.  I would like the pattern result to include 2nd hyphen and everything proceeding the hyphen, including the hyphen itself (in bold).

 

11111 - Test, User - Document Name - Optional Name

 

Thanks in advance!

 

0 0

Answer

SELECTED ANSWER
replied on November 18, 2019 Show version history

This should do the trick:

-[^-]*-[^-]*$

Helps to read the pattern backwards to understand the logic:

  1. Starting from the end of the input ($)
  2. Match any number of any characters other than a hyphen ([^-]*)
  3. Then match the hyphen (-)
  4. Repeat 2 & 3 to match the next words and second hyphen

 

Edit: I noticed the part after the third hyphen is "Optional Name". This pattern doesn't work correctly if the third hyphen isn't there. 

Here's another option that works the other direction:

^(?:[^-]*-[^-]*)(.*)
  1. Starting from the beginning of the input (^)
  2. In a non-capture group ((?:)), match everything up to the second hyphen ([^-]*-[^-]*)
  3. Then in a capture group, match everything remaining (.*)
0 0
replied on November 18, 2019

Perfect!  Thanks so much.

0 0
replied on November 18, 2019 Show version history

Welcome! Take a look at the edit I made a moment ago with a caveat and alternate pattern. 

0 0

Replies

You are not allowed to reply in this post.
You are not allowed to follow up in this post.

Sign in to reply to this post.