NotAgain
NotAgain

Reputation: 1977

Need regex to strip away remaing part of a path

I am trying to write a regex which will strip away the rest of the path after a particular folder name.

If Input is:

/Repository/Framework/PITA/branches/ChangePack-6a7B6/core/src/Pita.x86.Interfaces/IDemoReader.cs

Output should be:

/Repository/Framework/PITA/branches/ChangePack-6a7B6

Some constrains: ChangePack- will be followed change pack id which is a mix of numbers or alphabets a-z or A-Z only in any order. And there is no limit on length of change pack id. ChangePack- is a constant. It will always be there.

And the text before the ChangePack can also change. Like it can also be:

/Repository/Demo1/Demo2/4.3//PITA/branches/ChangePack-6a7B6/core/src/Pita.x86.Interfaces

My regex-fu is bad. What I have come up with till now is:

^(.*?)\-6a7B6

I need to make this generic. Any help will be much appreciated.

Upvotes: 0

Views: 41

Answers (4)

vks
vks

Reputation: 67968

^(.*?ChangePack-[a-zA-Z0-9]+)

Try this.Instead of replace grab the match $1 or \1.See demo.

https://regex101.com/r/iY3eK8/17

Upvotes: 1

Kannan Mohan
Kannan Mohan

Reputation: 1840

Below regex can do the trick.

^(.*?ChangePack-[\w]+)

Input:

/Repository/Framework/PITA/branches/ChangePack-6a7B6/core/src/Pita.x86.Interfaces/IDemoReader.cs
/Repository/Demo1/Demo2/4.3//PITA/branches/ChangePack-6a7B6/core/src/Pita.x86.Interfaces

Output:

/Repository/Framework/PITA/branches/ChangePack-6a7B6
/Repository/Demo1/Demo2/4.3//PITA/branches/ChangePack-6a7B6

Check out the live regex demo here.

Upvotes: 1

Gillespie
Gillespie

Reputation: 6561

Instead of regex you could can use split and join functions. Example python:

path = "/a/b/c/d/e"
folders = path.split("/")
newpath = "/".join(folders[:3]) #trims off everything from the third folder over
print(newpath) #prints "/a/b"

If you really want regex, try something like ^.*\/folder\/ where folder is the name of the directory you want to match.

Upvotes: 0

Geoff Penny
Geoff Penny

Reputation: 81

Will you always have '/Repository/Framework/PITA/branches/' at the beginning? If so, this will do the trick:

/Repository/Framework/PITA/branches/\w+-\w*

Upvotes: 0

Related Questions