0

I have been stuck for some time developing a single regex to extract a path from either of the following strings :

1.  "life:living:fast"
2.  "life"
3.  ":life"
4.  ":life:"

I have these regex expressions to use :

(.{3,}):", ":(.{3,}):", ":(.{3,})", "(.{3,})

The first match is all I need. i.e. the desired result for each should be the string located where the word life is. consider life to be a variable

But for some reason combining these individual regex's is a pain: If I excecute them sequentially I get the word 'life' extracted. However I am unable to combine them into one.

I appreciate your effort.

5
  • 2
    Not very clear what you're asking... can you post some desired input vs output? Commented Jun 19, 2014 at 10:10
  • @Mena please see my edit, the desired result for each should be the string located where the word life is. Commented Jun 19, 2014 at 10:13
  • 1
    Still unclear. So you want to find whether "life" is contained within your Strings? Or you want the index of "life"? Or...? Commented Jun 19, 2014 at 10:15
  • @Mena consider life to be a place holder or a variable, i.e the string could be *1:*2:*3 or *1 or :*1 or :*1: where *1 is a string that does not contain : Commented Jun 19, 2014 at 10:19
  • 1
    Yes but it's still unclear what you want to do with it. Posting some input vs output might help a great deal here. Commented Jun 19, 2014 at 10:21

2 Answers 2

2

If you want the first life with the colons, you can use this:

^:?(?:.{3,}?)(?::|$)

See demo

If you prefer the first life without the colons, switch to this:

((?<=^:)|^)([^:]{3,}?)(?=:|$)

See demo

How it Works #1: ^:?(?:.{3,}?)(?::|$)

  • With ^:?, at the beginning of the string, we match an optional colon
  • (?:.{3,}?) lazily matches three or more chars up to...
  • (?::|$) a colon or the end of the string

How it Works #1: ((?<=^:)|^)([^:]{3,}?)(?=:|$)

  • ((?<=^:)|^) ensures that we are either positioned at the beginning of the string, or after a colon immediately after the beginning of the string
  • ([^:]{3,}?) lazily matches chars that are not colons...
  • up to a point where the lookahead (?=:|$) can assert that what follows is a colon or the end of the string.
Sign up to request clarification or add additional context in comments.

Comments

2

You can use this pattern, since you are looking for the first word:

(?<=^:?)[^:]{3,}

Note that this pattern doesn't check all the string.

1 Comment

It works too and is precise. but I will stick to zx81's answer as it is broken down to my simple understanding.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.