0

The title may be not appropriate but that I am trying to do is to cut url in certain condition. I want to create an regex which will throw away '/' at the end of the link.

For example

http://stackoverflow.com/questions/ask/
to
http://stackoverflow.com/questions/ask

I was able to archieve this with this ^(.*)\/(example) but now I needed a change, and I'm not sure how it supposed to look.

Basically, the change I need is to DON'T touch the '/' if it is main page:

http://stackoverflow.com/ stays http://stackoverflow.com/
http://stackoverflow.com/questions/ changes to ttp://stackoverflow.com/questions

From my point of view it supposes to look if url are ended with text between two '/' and without any '.', but so far I am failing to make this condition.

How it potentially supposed to look?

EDIT

Some of the url may not contain http or https, so for me it is totally ok if regex regex will work on a normal text to.

Olegs Jasjko
  • 1,620
  • 4
  • 22
  • 41

5 Answers5

0

If URL starts with http:// or https:// you can use following pattern.

(http[s]*://.*?/.*)/$
Gokhan Celikkaya
  • 537
  • 1
  • 5
  • 17
0

This process can help:

^(http[s]?:\/\/[^\/]*)(.*)\/

Required URL = Group 1. + Group 2.

if Group 2 empty then
   1. It is main Url 
   2. Add "/" at the end
else 
   1. It is **not** main URL
   2. Keep it as it is

[Regex Demo]

0

You're looking to throw away the forward slash if it's just a trailing character and keep it if it denotes some kind of path in your website.

All that requires is checking whether the forward slash is the last character (I'm pretty sure that's the simplest way of going about it).

(?(?=\/$)(.+)\/)

This regex uses an if statement to check whether the forward slash is the last character, and in which case matches everything up until the forward slash.

JackHasaKeyboard
  • 1,393
  • 1
  • 13
  • 26
0

Use this :

(.*\.[a-z]+\/?(?:[\w]+(?:\/[\w]+)*)*)

The result will be stored in Group1, see example here https://regex101.com/r/egAQvX/6

0

… Following your current logic, the pattern you may use is /^(?!(?:[^:]+:\/\/)?[^\/]+\/$)(.*)\/$/. Or maybe exclude whitespaces: /^(?!(?:[^\s:]+:\/\/)?[^\/\s]+\/$)(.*)\/$/ – Wiktor Stribiżew

Armali
  • 14,228
  • 13
  • 47
  • 141