How to extract youtube video id with Regex.Match - regex

i try to extract video ID from youtube using Regex.Match, for example I have www.youtube.com/watch?v=3lqexxxCoDo and i want to extract only 3lqexxxCoDo.
Dim link_vids As Match = Regex.Match(url_comments.Text, "https://www.youtube.com/watch?v=(.*?)$")
url_v = link_vids.Value.ToString
MessageBox.Show(url_v)
how i can extract video id ?, thanks !

Finally got the solution
Dim Str() As String
Str = url_comments.Text.Split("=")
url_v = Str(1)

Private Function getID(url as String) as String
Try
Dim myMatches As System.Text.RegularExpressions.Match 'Varible to hold the match
Dim MyRegEx As New System.Text.RegularExpressions.Regex("youtu(?:\.be|be\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)", RegexOptions.IgnoreCase) 'This is where the magic happens/SHOULD work on all normal youtube links including youtu.be
myMatches = MyRegEx.Match(url)
If myMatches.Success = true then
Return myMatches.Groups(1).Value
Else
Return "" 'Didn't match something went wrong
End If
Catch ex As Exception
Return ex.ToString
End Try
End Function
This function will return just the video ID.

you can basically replace "www.youtube.com/watch?v=" with "" using "String.Replace"
MSDN String.Replace
url.Replace("www.youtube.com/watch?v=","")

You can use this expression, in PHP I am using this.
function parseYtId($vid)
{
if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $vid, $match)) {
$vid = $match[1];
}
return $vid;
}

Related

Append value of an XML Element with additional text using regular expressions

I am trying to convert the following in an XML
<SharedDataSetReference>AnyDataSetName</SharedDataSetReference>
to
<SharedDataSetReference>/DataSets/AnyDataSetName</SharedDataSetReference>
at the same time, existing instances of
<SharedDataSetReference>/DataSets/AnyDataSetName</SharedDataSetReference>
should remain unchanged.
Pls note that AnyDataSetName can have
<SharedDataSetReference>Company</SharedDataSetReference>
<SharedDataSetReference>Customer</SharedDataSetReference>
or
/Datasets/Order
and they should change to
<SharedDataSetReference>/Datasets/Company</SharedDataSetReference>
<SharedDataSetReference>/Datasets/Customer</SharedDataSetReference>
<SharedDataSetReference>/Datasets/Order</SharedDataSetReference>
Try this
<SharedDataSetReference>([^\/]+)<\/SharedDataSetReference>
https://regex101.com/r/yM7tA0/1
Thanks Tim007
This is what i did
var sharedDatasets = Regex.Replace(datasets.First().ToString(), String.Format(#"<{0}>(?<DataSetReferenceValue>[^\/]+)<\/{0}>", "SharedDataSetReference"), delegate(Match match)
{
var value = String.Concat("/Datasets/", match.Groups["DataSetReferenceValue"].ToString());
return String.Format(#"<{0}>{1}</{0}>", "SharedDataSetReference", value);
}, RegexOptions.Multiline
)

String replace with dictionary exception handling

I've implemented the answer here to do token replacements of a string:
https://stackoverflow.com/a/1231815/1224021
My issue now is when this method finds a token with a value that is not in the dictionary. I get the exception "The given key was not present in the dictionary." and just return the normal string. What I'd like to happen obviously is all the good tokens get replaced, but the offending one remains au naturale. Guessing I'll need to do a loop vs. the one line regex replace? Using vb.net. Here's what I'm currently doing:
Shared ReadOnly re As New Regex("\$(\w+)\$", RegexOptions.Compiled)
Public Shared Function GetTokenContent(ByVal val As String) As String
Dim retval As String = val
Try
If Not String.IsNullOrEmpty(val) AndAlso val.Contains("$") Then
Dim args = GetRatesDictionary()
retval = re.Replace(val, Function(match) args(match.Groups(1).Value))
End If
Catch ex As Exception
' not sure how to handle?
End Try
Return retval
End Function
The exception is likely thrown in the line
retval = re.Replace(val, Function(match) args(match.Groups(1).Value))
because this is the only place you are keying the dictionary. Make use of the Dictionary.ContainsKey method before accessing it.
retval = re.Replace(val,
Function(match)
return If(args.ContainsKey(match.Groups(1).Value), args(match.Groups(1).Value), val)
End Function)
This is what I got to work vs. the regex, which was also a suggestion on the original thread by Allen Wang: https://stackoverflow.com/a/7957728/1224021
Public Shared Function GetTokenContent(ByVal val As String) As String
Dim retval As String = val
Try
If Not String.IsNullOrEmpty(val) AndAlso val.Contains("$") Then
Dim args = GetRatesDictionary("$")
retval = args.Aggregate(val, Function(current, value) current.Replace(value.Key, value.Value))
End If
Catch ex As Exception
End Try
Return retval
End Function
I know it's been a while since this question was answered, but FYI for anyone wanting to still use the Regex / Dictionary match approach, the following works (based on the sample in the OP question):
retVal = re.Replace(formatString,
match => args.ContainsKey(match.Groups[1].Captures[0].Value)
? args[match.Groups[1].Captures[0].Value]
: string.Empty);
... or my full sample as a string extension method is:
public static class StringExtensions
{
// Will replace parameters enclosed in double curly braces
private static readonly Lazy<Regex> ParameterReplaceRegex = new Lazy<Regex>(() => new Regex(#"\{\{(?<key>\w+)\}\}", RegexOptions.Compiled));
public static string InsertParametersIntoFormatString(this string formatString, string parametersJsonArray)
{
if (parametersJsonArray != null)
{
var deserialisedParamsDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(parametersJsonArray);
formatString = ParameterReplaceRegex.Value.Replace(formatString,
match => deserialisedParamsDictionary.ContainsKey(match.Groups[1].Captures[0].Value)
? deserialisedParamsDictionary[match.Groups[1].Captures[0].Value]
: string.Empty);
}
return formatString;
}
}
There are a few things to note here:
1) My parameters are passed in as a JSON array, e.g.: {"ProjectCode":"12345","AnotherParam":"Hi there!"}
2) The actual template / format string to do the replacements on has the parameters enclosed in double curly braces: "This is the Project Code: {{ProjectCode}}, this is another param {{AnotherParam}}"
3) Regex is both Lazy initialized and Compiled to suit my particular use case of:
the screen this code serves may not be used often
but once it is, it will get heavy use
so it should be as efficient on subsequent calls as possible.

Regular Expression Matcher

I am using pattern matching to match file extension with my expression String for which code is as follows:-
public static enum FileExtensionPattern
{
WORDDOC_PATTERN( "([^\\s]+(\\.(?i)(txt|docx|doc))$)" ), PDF_PATTERN(
"([^\\s]+(\\.(?i)(pdf))$)" );
private String pattern = null;
FileExtensionPattern( String pattern )
{
this.pattern = pattern;
}
public String getPattern()
{
return pattern;
}
}
pattern = Pattern.compile( FileExtensionPattern.WORDDOC_PATTERN.getPattern() );
matcher = pattern.matcher( fileName );
if ( matcher.matches() )
icon = "blue-document-word.png";
when file name comes as "Home & Artifact.docx" still matcher.matches returns false.It works fine with filename with ".doc" extension.
Can you please point out what i am doing wrong.
"Home & Artifact.docx" contains spaces. Since you allow any char except whitespaces [^\s]+, this filename is not matched.
Try this instead:
(.+?(\.(?i)(txt|docx|doc))$
It is because you have spaces in filename ("Home & Artifact.docx") but your regex has [^\\s]+ which won't allow any spaces.
Use this regex instead for WORDDOC_PATTERN:
"(?i)^.+?\\.(txt|docx|doc)$"

Regex- Get file name after last '\'

I have file name like
C:\fakepath\CI_Logo.jpg.
I need a regex for getting CI_Logo.jpg. Tried with \\[^\\]+$, but didn't workout..
Below is my Javascript Code
var regex="\\[^\\]+$";
var fileGet=$('input.clsFile').val();
var fileName=fileGet.match(regex);
alert(fileName);
Minimalist approach: demo
([\w\d_\.]+\.[\w\d]+)[^\\]
Use this
String oldFileName = "slashed file name";
String[] fileNameWithPath = oldFileName.split("\\\\");
int pathLength = fileNameWithPath.length;
oldFileName = fileNameWithPath[pathLength-1];
in java,
I guess,You can modify this for any other langs.
Edit:
make sure you split with "\\\\" - four slashes

use regex to check if string/url does not begin with specified string

[RegularExpression(), ErrorMessage = "Youtube link must start with www.youtube.com/watch?v=")]
I need to check if Link does NOT begin with: http://www.youtube.com/watch?v=
I've just created an MVC project and tested the following:
[RegularExpression("^((?!http://www.youtube.com/watch\\?v=).)*$")]
This seems to work.
More information may be found here.
If you need to check that the text does begin with a youtube link (rather than does not begin) then you can use:
[RegularExpression("http://www.youtube.com/watch\\?v=.*")]
Try this code , Alan
using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string txt="http://www.youtube.com/watch?v=";
string re1="(http:\\/\\/www\\.youtube\\.com\\/watch\\?v=)";
string re2="(www\\.youtube\\.com)";
Regex r = new Regex(re1+re2,RegexOptions.IgnoreCase|RegexOptions.Singleline);
Match m = r.Match(txt);
if (m.Success)
{
String httpurl1=m.Groups[1].ToString();
String file1=m.Groups[2].ToString();
Console.Write("("+httpurl1.ToString()+")"+"("+file1.ToString()+")"+"\n");
}
Console.ReadLine();
}
}
}
If you only want to check for that specific string, regex is not needed.
just do something like int position = string.IndexOf("http://www.youtube.com/watch?v="); and check if position is 0
EDIT:
If you really need a regular expression you could try this: /^(?!^http:\/\/www\.youtube\.com/watch\?v=).*/