I have a URL and need to extract the port, username and password from it and put them into an array. It looks like following.
http://myproject.ddns.net:8080/get.php?username=9zu7T54rt6&password=1Tbliu49iH&type=m3u_plus&output=ts
Can I use some other method without replaces or substring?
One of the ways in C#
Get the query parameter
var parsedQuery = HttpUtility.ParseQueryString("http://myproject.ddns.net:8080/get.php?username=9zu7T54rt6&password=1Tbliu49iH&type=m3u_plus&output=ts");
Then, below will give the username
parsedQuery["username"]
For Password:
parsedQuery["password"]
For port you can use URI :
Uri uri = new Uri("http://myproject.ddns.net:8080/get.php?username=9zu7T54rt6&password=1Tbliu49iH&type=m3u_plus&output=ts");
Get the port by
uri.Port
Create an array or use whatever you require to club.
I don't know C#, but here's one that works for Python. It's pretty straightforward so you should be able to convert.
:(?P<port>[0-9]+).*username=(?P<username>[a-zA-Z0-9]+).*password=(?P<password>[a-zA-Z0-9]+)
The (?P<foo>bar) syntax is a named capture group that will put a variable matching the pattern 'bar' into a variable called 'foo' when you extract them.
Here is another possible solution with pure C# regex:
var url = "http://myproject.ddns.net:8080/get.php?username=9zu7T54rt6&password=1Tbliu49iH&type=m3u_plus&output=ts";
var urlRegex = new Regex(#"(?<=(http(s)?://)?\w+(\.\w+)*:)\d+(?=/.*)?");
var usernameRegex = new Regex(#"(?<=(\?|&)username=).*?(?=&|$)", RegexOptions.IgnoreCase);
var passwordRegex = new Regex(#"(?<=(\?|&)password=).*?(?=&|$)", RegexOptions.IgnoreCase);
Console.WriteLine(urlRegex.Match(url));
Console.WriteLine(usernameRegex.Match(url));
Console.WriteLine(passwordRegex.Match(url));
If there are any parts that don't change, e.g. if it's always the same url you could just replace it like this
string str = "http://myproject.ddns.net:8080/get.php?username=9zu7T54rt6&password=1Tbliu49iH&type=m3u_plus&output=ts"
str.Replace("http://myproject.ddns.net","");
This would leave you ":8080/get.php?username=9zu7T54rt6&password=1Tbliu49iH&type=m3u_plus&output=ts"
There is nothing stopping you repeating the process with another section.
As for regex you could use Regex.Match https://msdn.microsoft.com/en-us/library/twcw2f1c(v=vs.110).aspx to get the parts you want.
You could use ":\d{4}/" to get the port - you'd have to strip the leading ":" and trailing "/" though; this "username=\w*\&" to get the username - you'd have to strip the leading "username=" and trailing "&" though; and for the password you could use "password=\w*\&" - you'd have to strip the leading "password=" and trailing "&" though.
If you'd like to experiment with regex this site https://regex101.com/ is pretty good.
Related
i am doing a project , and i want to remove from a string http protocoll. In my excel sheet there are two types one is http://www.email#domain.com and the other is http://email#domain.com.I have tried so many combinations but i can't find the right one.
My code only works with the first type and not with the second one
var website_domain_in_excel = list_of_information_in_excel[2];
string pattern = "(http://\\www.)";
Console.WriteLine(Regex.Replace(website_domain_in_excel, pattern, String.Empty));
Thank you for your time
The pattern you want is this:
string pattern = #"http:\/\/(?:www\.)?"
This matches http:// and then an optional non-capturing group matching www..
You can see an explanation of the regex here and this fiddle for a working demo in C#.
You can use the string: "http?://?www.|http?://" which matches either "http://www." or "http://".
The code would look like this:
var website_domain_in_excel = list_of_information_in_excel[2];
string pattern = #"http:\/\/www.|http:\/\/";
Console.WriteLine(Regex.Replace(website_domain_in_excel, pattern, String.Empty));
A non-regex solution:
var eml = "http://www.email#domain.com";
eml = eml.Replace("http://", "").Replace("www.", "");
// eml now is "email#domain.com"
You might want to test that that "www." only appears at the start. The (unusual) "email#www.domain.com" should remain intact.
But if you really want a regex:
eml = Regex.Replace(eml, "^https?://(www\\.)?", "");
This also catches "https", because of the ? after that "s"
It will also find and replace an optional "www.", but only at the start
Hi all I need to extract Guid from the following string
<PageFieldFieldValue:FieldValue FieldName='fa564e0f-0c70-4ab9-b863-0177e6ddd247' runat='server'></PageFieldFieldValue:FieldValue>
<PageFieldRichImageField:RichImageField FieldName="3de94b06-4120-41a5-b907-88773e493458" runat="server"></PageFieldRichImageField:RichImageField>
What i need is to get is "fa564e0f-0c70-4ab9-b863-0177e6ddd247" and "3de94b06-4120-41a5-b907-88773e493458" in this case, However this guid is dynamic and will change every time and there are lot more guids in the string that i have and I need to get all those guids so that I can add them to a colection.
Note: The string is actually an aspx page content. All nodes are different but have same property "FieldName" which I need to get.
I went through the link C# RegEx string extraction and construcked the regex in same way. Here is what I did :
string s = #"<PageFieldFieldValue:FieldValue FieldName='fa564e0f-0c70-4ab9-b863-0177e6ddd247' runat='server'>
</PageFieldFieldValue:FieldValue>";
Regex reg = new Regex(#"FieldName=(?<ReferenceId>{36})");
Match match = reg.Match(s);
string guid = match.Groups["ReferenceId"].Value;
How ever this didnt work for me. I get exception"parsing "FieldName=(?{35})" - Quantifier {x,y} following nothing." while creating the Regex object "reg".
If i dont use {36} which is suppose to be the length of GUiD:
Regex reg = new Regex(#"FieldName=(?<ReferenceId>)")
I dont get any exception but I dnt get desired result either. match.Groups["ReferenceId"].Value returns empty string
Try using sth. like that:
(?<=FieldName=['"])[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}(?=['"])
Explanation
(?<=FieldName=['"]) prepended by FieldName= and " or '
[a-f\d]{8}-[a-f\d][...] followed by GUID (which is what is actually matching)
(?=['"]) followed by " or '
See this in action at Regex101
The issue you are having is basically that you are providing the quantifier {36} but are not telling it what to quantify - you need some character matching expression right before the quantifier. For, example I just added the '.' before {36} in your example (meaning "match any 36 characters") and it seems to work. Oh, and I also added the missing apostrophe after "FieldName=":
Regex reg = new Regex(#"FieldName='(?<ReferenceId>.{36})");
Working example: https://regex101.com/r/1tbien/1
In my application, I must read a URL and do something if the URL contains Basic authentication credentials. An example of such a URL is
http://username:password#example.com
Is the regular expression below a good fit for my task? I am to capture four groups into local variables. The URL is passed to another internal library that will do further work to ensure the URL is valid before opening a connection.
^(.+?//)(.+?):(.+?)#(.+)$
It looks ok, and I think that a regular expression is good to use in this case. A couple of suggestions:
1) I think that named groups would make your code more readable, i.e:
^(?<protocol>.+?//)(?<username>.+?):(?<password>.+?)#(?<address>.+)$
Then you can simply write
Match match = Regex.Match(string, pattern);
if (match.Success) {
string user = match.Groups["username"];
2) then you could make the expression a little more strict, e.g. using \w when possible instead of .:
^(?<protocol>\w+://)...
Your regex seems OK, but why not use the thoroughly-tested and nearly-compliant Uri class? It's then trivial to access the pieces you want without worrying about spec-compatibility:
var url = new Uri("http://username:password#example.com");
var userInfo = url.UserInfo.Split(':');
var username = userInfo[0];
var password = userInfo[1];
Got this regex string from "JavaScript: the good parts" (pp. 66). Can't get it to work. Can anyone see what is wrong with it?
/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/
it's supposed to split up a string like this:
https://stackoverflow.com/questions/ask
into constituents: scheme, slash, host, port, path, query, hash
btw: this regex needs to be generic... it's going to be used on different "schemes"
Maybe this isn't your goal, but why don't you use System.Uri class?
It has what you want and it parses raw URI/URL(s).
http://msdn.microsoft.com/en-us/library/system.uri.aspx
your question is tagged with c#, so why don't you just use the System.Uri class?
eg
string s = "http://stackoverflow.com/questions/ask";
Uri uri = new System.Uri(s);
string scheme = uri.Scheme;
string host = uri.DnsSafeHost;
// etc
If this is in Javascript try
result = subject.match(/\b(https?|ftp):\/\/([\-A-Z0-9.]+)(\/[\-A-Z0-9+&##\/%=~_|!:,.;]*)?(\?[A-Z0-9+&##\/%=~_|!:,.;]*)?/ig);
I really don't know, what is the meaning of all parts of regex, but the last # character should be escaped by backslash.
/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:\#(.*))?$/
I am consuming the Twitter API and want to convert all URLs to hyperlinks.
What is the most effective way you've come up with to do this?
from
string myString = "This is my tweet check it out http://tinyurl.com/blah";
to
This is my tweet check it out http://tinyurl.com/>blah
Regular expressions are probably your friend for this kind of task:
Regex r = new Regex(#"(https?://[^\s]+)");
myString = r.Replace(myString, "$1");
The regular expression for matching URLs might need a bit of work.
I did this exact same thing with jquery consuming the JSON API here is the linkify function:
String.prototype.linkify = function() {
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
This is actually an ugly problem. URLs can contain (and end with) punctuation, so it can be difficult to determine where a URL actually ends, when it's embedded in normal text. For example:
http://example.com/.
is a valid URL, but it could just as easily be the end of a sentence:
I buy all my witty T-shirts from http://example.com/.
You can't simply parse until a space is found, because then you'll keep the period as part of the URL. You also can't simply parse until a period or a space is found, because periods are extremely common in URLs.
Yes, regex is your friend here, but constructing the appropriate regex is the hard part.
Check out this as well: Expanding URLs with Regex in .NET.
You can add some more control on this by using MatchEvaluator delegate function with regular expression:
suppose i have this string:
find more on http://www.stackoverflow.com
now try this code
private void ModifyString()
{
string input = "find more on http://www.authorcode.com ";
Regex regx = new Regex(#"\b((http|https|ftp|mailto)://)?(www.)+[\w-]+(/[\w- ./?%&=]*)?");
string result = regx.Replace(input, new MatchEvaluator(ReplaceURl));
}
static string ReplaceURl(Match m)
{
string x = m.ToString();
x = "< a href=\"" + x + "\">" + x + "</a>";
return x;
}
/cheer for RedWolves
from: this.replace(/[A-Za-z]+://[A-Za-z0-9-]+.[A-Za-z0-9-:%&\?/.=]+/, function(m){...
see: /[A-Za-z]+://[A-Za-z0-9-]+.[A-Za-z0-9-:%&\?/.=]+/
There's the code for the addresses "anyprotocol"://"anysubdomain/domain"."anydomainextension and address",
and it's a perfect example for other uses of string manipulation. you can slice and dice at will with .replace and insert proper "a href"s where needed.
I used jQuery to change the attributes of these links to "target=_blank" easily in my content-loading logic even though the .link method doesn't let you customize them.
I personally love tacking on a custom method to the string object for on the fly string-filtering (the String.prototype.linkify declaration), but I'm not sure how that would play out in a large-scale environment where you'd have to organize 10+ custom linkify-like functions. I think you'd definitely have to do something else with your code structure at that point.
Maybe a vet will stumble along here and enlighten us.