user3755799
user3755799

Reputation:

Regex to Capture and replace

I have URL like this

I need to capture a text video and replace it with swf as follows:

If i use normal string.Replace, then it will replace the video text which may contained in file name of video, So i want to capture a video after domain and replace it with swf

Please help me out..

I have tried this ^(http:\/\/(?:www.)?(?:dailymotion).com\/)\?(video)$ but dont know how much is it right...

Upvotes: 1

Views: 471

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174706

Try the below regexes and replace the second capturing group with swf,

^(http:\/\/(?:www\.)?dailymotion\.com\/)([^\/]*)(.*)$

DEMO

OR

^(http:\/\/(?:www\.)?dailymotion\.com\/)(video)(.*)$

DEMO

From starting, characters upto the string .com/ are captured by the first the group. Next the characters upto the next forward slash are captured by second group(ie, video). All the remaining characters are captured by third group. Just replacing the second captured group in your case it's video with swf will give you the desired result.

Upvotes: 0

zx81
zx81

Reputation: 41838

Search (http://\S+/)video(/\S+), replace with $1swf$2

In VB.NET:

Dim ResultString As String
Try
    ResultString = Regex.Replace(SubjectString, "(http://\S+/)video(/\S+)", "$1swf$2", RegexOptions.IgnoreCase)
Catch ex As ArgumentException
    'Syntax error in the regular expression
End Try

Explanation

  • The regex matches the string in three parts: Group 1, video, Group 2, and we replace that with Group 1, swf, Group 2
  • (http://\S+/) captures to Group 1 http//, any chars that are not a white-space, and a forward slash
  • video matches literal characters
  • (/\S+) captures to Group 2 any chars that are not white-space characters

Upvotes: 1

Related Questions