2

I need to build a regular expression that accepts the following pattern:

word1/word2/*
word1/*

word2 is optional, and it needs to end with /*.

I tried this regexp:

(word1)/(word2)?/\*

It matches this input: word1/word2/*

but not this: word1/*

1
  • Do you need to capture the values of word1 and word2?
    – Michelle
    Mar 10, 2014 at 18:11

3 Answers 3

2

Try this:

word1(?:/word2)?/\*

The (?: ) construct is a non-capturing group. The ? after it means "zero or one of the previous atom." So this matches word1 optionally followed by /word2, then a final slash and asterisk.

(I'm assuming that's a literal asterisk that you want to match, not a wildcard asterisk as in "any characters"; if it's the latter you want, replace \* with .*.)

(You can put the capturing groups () back in on word1 and word2 if you need them.)

2
  • 1
    This won't capture the values of word1 and word2, which it seems OP wants to do based on the current regex, but hopefully they'll confirm whether this is the case.
    – Michelle
    Mar 10, 2014 at 18:13
  • @Michelle Added a note to the answer. Thanks.
    – TypeIA
    Mar 10, 2014 at 18:15
0

You need to move the first / into the following capture group (parenthesized subexpression):

(word1)(/word2)?/\*

If you want to capture word2 without the leading /, introduce an additional capture group:

(word1)(/(word2))?/\*

Note:

  • Depending on your specific environment, you may be able to avoid unneeded capture groups via non-capturing groups ((?:...)).
1
  • Note: This answer is - indirectly - discussed on Meta SO
    – mklement0
    Oct 23, 2023 at 21:21
0

I have another answer, I believe its more lean.

(((word)(1|2)/){1,2}\*)

Much less code, try it out.

1
  • I think it is fair to assume that word1 and word2 in the question are merely placeholders, so they shouldn't be assumed to share a common prefix / fixed suffixes.
    – mklement0
    Oct 23, 2023 at 21:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.