开发者

Capture arbitrary string before either '/' or end of string

开发者 https://www.devze.com 2023-02-05 16:02 出处:网络
Suppose I have: foo/fhqwhgads foo/fhqwhgadshgnsdhjsdbkhsdabkfabkveybvf/bar And I want to replace everything that follows \'foo/\' up until I either reach \'/\' or, if \'/\' is ne开发者_JAVA技巧ver

Suppose I have:

foo/fhqwhgads
foo/fhqwhgadshgnsdhjsdbkhsdabkfabkveybvf/bar

And I want to replace everything that follows 'foo/' up until I either reach '/' or, if '/' is ne开发者_JAVA技巧ver reached, then up to the end of the line. For the first part I can use a non-capturing group like this:

(?<=foo\/).+

And that's where I get stuck. I could match to the second '/' like this:

(?<=foo\/).+(?=\/)

That doesn't help for the first case though. Desired output is:

foo/blah
foo/blah/bar

I'm using Ruby.


Try this regex:

/(?<=foo\/)[^\/]+/


Implementing @Endophage's answer:

def fix_post_foo_portion(string)
  portions = string.split("/")
  index_to_replace = portions.index("foo") + 1
  portions[index_to_replace ] = "blah"
  portions.join("/")
end

strings = %w{foo/fhqwhgads foo/fhqwhgadshgnsdhjsdbkhsdabkfabkveybvf/bar}
strings.each {|string| puts fix_post_foo_portion(string)}


I'm not a ruby dev but is there some equivalent of php's explode() so you could explode the string, insert a new item at the second array index then implode the parts with / again... Of course you can match on the first array element if you only want to do the switch in certain cases.


['foo/fhqwhgads', 'foo/fhqwhgadshgnsdhjsdbkhsdabkfabkveybvf/bar'].each do |s|
  puts s.sub(%r|^(foo/)[^/]+(/.*)?|, '\1blah\2')
end

Output:

foo/blah
foo/blah/bar

I'm too tired to think of a nicer way to do it but I'm sure there is one.


Checking for the end-of-string anchor -- $ -- as well as the / character should do the trick. You'll also need to make the .+ non-greedy by changing it to .+? since the greedy version will always match right up to the end of the string, given the chance.

(?<=foo\/).+?(?=\/|$)
0

精彩评论

暂无评论...
验证码 换一张
取 消