string.split parse url from large string - c#

How would I parse and extract the url from this large string of text in the image below?
I want the .m3u8 link.
I tried using String.split() but that only accepts chars and not strings.

I dont know this approach would be right but I guess you can remove those lines containing "EXT" if they are common in your url.
var result = url.Split(new [] { '\r', '\n' }); // converting string to lines
for (int i=0;i<=result.Length-1;i++) // Finding if EXT text is present and removing them
{
if (result[i].Contains("EXT-")
result.RemoveAt(i);
}
string final = string.Join("", result); // converting back to string
Tell me if it works for you!

How would I parse and extract the url from this large string of text?
use this code:
void Main()
{
var text = #"
otEXT-X-MEDIA:TYPE=VIDEO,GROUP-ID=720p30',NAME=*720p°,AUTOSELECT=YES,DEFAULT=YESEXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2374703,RESOLUTION=1280x720,CODECS=•avc1.77.31,mp4a.40.2',VIDEO=720p30'
http://video-weaver.lax03.hls.tbmw.net/v1/playlist/CuoCf3YooUjSfbk71Zs3ig68T2vDVg7449mAN78mSV1oQ9V7skuTh6NP9FOSaIgGNgnpliscdDC9XvjGyGcYrIXBbAXSkqCGuIOTQgtIw5IQLUIbHGMZIXWZeD6Urd4GzyPxCoARIYyo6i5ECCfK2r1jW1kidXGotcRXy6fHolJw-rC9xPPYc2IxYKaERQ9NsOMGn3m2ChqWFSpRHbYNK1M8OrU4WecMwgoFkORbEBEmAmng2V8GnGz63hWNV2sDW1H9E5pYjG4jpPLEf_Fwt75CePIgyZ9g30Kgr5CHZYSyMMbMAX-eac5wC3wjVUWtGz094t4xH1713yvWjv813vCY6NRBCPkCINdpXBmUnLcnE1JOLye_NiGx5R1B4IMDpRXDZQAO6PBm97ZNhyLZKc9Awg5vypphWG2MMAGdboca5WGtG_wVRp12SiHw9n0a51VpqNjVVVWbASuUly-CEe22tzLkwEolOWGE8VQSECyPx17qBU7YPHCEEi8ncnMaDly1Dn8j0xU-QN71kA.m3u8
";
MatchCollection ms = Regex.Matches(text, #"(www.+|http.+)([\s]|$)");
string url = ms[0].Value.ToString();
Console.WriteLine(url);
}
I tried using String.Split but that only accepts chars and not strings.
this question you can use extension
but it's can't deal your problem
void Main()
{
var extention_str = "http://aaacccddd".Split("ccc");
}
public static class StrinExtention {
public static string [] Split(this string str,string separator){
return str.Split(new string [] {separator},StringSplitOptions.None);
}
}

Related

Read string word by word with .Substring?

I'v got the following String string gen = "Action;Adventure;Drama;Horror;
I tried to seperate the string word by word with .substring like: gen.Substring(gen.IndexOf(';')+1, gen.IndexOf(';'))
But my output is just "Advent".
Any help?
Background: The string collects the names of checkboxes that are checked. The string is then saved in a database.
I want to read out the string an check each checkbox on another form.
Just split it:
var parts = gen.Split(';');
(Then you can iterate over that via foreach.)
Split it like this:
public class Example
{
public static void Main()
{
String value = "Action;Adventure;Drama;Horror";
Char delimiter = ';';
String[] substrings = value.Split(delimiter);
foreach (var substring in substrings)
Console.WriteLine(substring);
}
}

Delimit a string by character unless within quotation marks C#

I need to demilitarise text by a single character, a comma. But I want to only use that comma as a delimiter if it is not encapsulated by quotation marks.
An example:
Method,value1,value2
Would contain three values: Method, value1 and value2
But:
Method,"value1,value2"
Would contain two values: Method and "value1,value2"
I'm not really sure how to go about this as when splitting a string I would use:
String.Split(',');
But that would demilitarise based on ALL commas. Is this possible without getting overly complicated and having to manually check every character of the string.
Thanks in advance
Copied from my comment: Use an available csv parser like VisualBasic.FileIO.TextFieldParser or this or this.
As requested, here is an example for the TextFieldParser:
var allLineFields = new List<string[]>();
string sampleText = "Method,\"value1,value2\"";
var reader = new System.IO.StringReader(sampleText);
using (var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(reader))
{
parser.Delimiters = new string[] { "," };
parser.HasFieldsEnclosedInQuotes = true; // <--- !!!
string[] fields;
while ((fields = parser.ReadFields()) != null)
{
allLineFields.Add(fields);
}
}
This list now contains a single string[] with two strings. I have used a StringReader because this sample uses a string, if the source is a file use a StreamReader(f.e. via File.OpenText).
You can try Regex.Split() to split the data up using the pattern
",|(\"[^\"]*\")"
This will split by commas and by characters within quotes.
Code Sample:
using System;
using System.Linq;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string data = "Method,\"value1,value2\",Method2";
string[] pieces = Regex.Split(data, ",|(\"[^\"]*\")").Where(exp => !String.IsNullOrEmpty(exp)).ToArray();
foreach (string piece in pieces)
{
Console.WriteLine(piece);
}
}
}
Results:
Method
"value1,value2"
Method2
Demo

Extract multiple values from string using C#

I'am creating my own forum. I've got problem with quoting messages. I know how to add quoting message into text box, but i cannot figure out how to extract values from string after post. In text box i've got something like this:
[quote IdPost=8] Some quoting text [/quote]
[quote IdPost=15] Second quoting text [/quote]
Could You tell what is the easiest way to extract all "IdPost" numbers from string after posting form ?.
by using a regex
#"\[quote IdPost=(\d+)\]"
something like
Regex reg = new Regex(#"\[quote IdPost=(\d+)\]");
foreach (Match match in reg.Matches(text))
{
...
}
var originalstring = "[quote IdPost=8] Some quoting text [/quote]";
//"[quote IdPost=" and "8] Some quoting text [/quote]"
var splits = originalstring.Split('=');
if(splits.Count() == 2)
{
//"8" and "] Some quoting text [/quote]"
var splits2 = splits[1].Split(']');
int id;
if(int.TryParse(splits2[0], out id))
{
return id;
}
}
I do not know exactly what is your string, but here is a regex-free solution with Substring :
using System;
public class Program
{
public static void Main()
{
string source = "[quote IdPost=8] Some quoting text [/quote]";
Console.WriteLine(ExtractNum(source, "=", "]"));
Console.WriteLine(ExtractNum2(source, "[quote IdPost="));
}
public static string ExtractNum(string source, string start, string end)
{
int index = source.IndexOf(start) + start.Length;
return source.Substring(index, source.IndexOf(end) - index);
}
// just another solution for fun
public static string ExtractNum2(string source, string junk)
{
source = source.Substring(junk.Length, source.Length - junk.Length); // erase start
return source.Remove(source.IndexOf(']')); // erase end
}
}
Demo on DotNetFiddle

Extract sub-directory name from URL in ASP.NET C#

I want to be able to extract the name of a sub-directory of a URL and save it to a string from the server-side in ASP.NET C#. For example, lets say I have a URL that looks like this:
http://www.example.com/directory1/directory2/default.aspx
How would I get the value 'directory2' from the URL?
Uri class has a property called segments:
var uri = new Uri("http://www.example.com/directory1/directory2/default.aspx");
Request.Url.Segments[2]; //Index of directory2
This is a sorther code:
string url = (new Uri(Request.Url,".")).OriginalString
I'd use .LastIndexOf("/") and work backwards from that.
You can use System.Uri to extract the segments of the path. For example:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var uri = new System.Uri("http://www.example.com/directory1/directory2/default.aspx");
}
}
Then the property "uri.Segments" is a string array (string[]) containing 4 segments like this: ["/", "directory1/", "directory2/", "default.aspx"].
You can use split method of string class to split it on /
Try this if you want to pick page directory
string words = "http://www.example.com/directory1/directory2/default.aspx";
string[] split = words.Split(new Char[] { '/'});
string myDir=split[split.Length-2]; // Result will be directory2
Here is example from MSDN. How to use split method.
using System;
public class SplitTest
{
public static void Main()
{
string words = "This is a list of words, with: a bit of punctuation" +
"\tand a tab character.";
string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });
foreach (string s in split)
{
if (s.Trim() != "")
Console.WriteLine(s);
}
}
}
// The example displays the following output to the console:
// This
// is
// a
// list
// of
// words
// with
// a
// bit
// of
// punctuation
// and
// a
// tab
// character

Splitting a string at every character

let's say I have a string "hello world". I would like to end up with " dehllloorw". As I don't find any ready-made solution I thought: I can split the string into a character array, sort it and convert it back to a string.
In perl I can do s// but in .Net I'd have to do a .Split() but there's no overload with no parameters... if I do .Split(null) it seems to split by whitespace and .Split('') won't compile.
how do I do this (I hate to run a loop!)?
Array.Sort("hello world".ToCharArray());
Below is a quick demo console app
class Program
{
static void Main(string[] args)
{
var array = "hello world".ToCharArray();
Array.Sort(array);
Console.WriteLine(new String(array));
Console.ReadLine();
}
}
The characters in a string can be directly used, the string class exposed them as an enumeration - combine that with Linq / OrderBy and you have a one-liner to create the ordered output string:
string myString = "hello world";
string output = new string(myString.OrderBy(x => x).ToArray()); // dehllloorw
You could always do this:
private static string SortStringCharacters(string value)
{
if (value == null)
return null;
return new string(value.ToList().Sort().ToArray());
}

Categories

Resources