提取C#中字符串的第一部分?
我正在寻找一种从链接中提取用户名的方法,一开始它将是子域 应用程序的用户可以选择输入用户名或配置文件的链接提取C#中字符串的第一部分?,c#,C#,我正在寻找一种从链接中提取用户名的方法,一开始它将是子域 应用程序的用户可以选择输入用户名或配置文件的链接 public static string GetUsernameFromLink(string link) { if (Uri.IsWellFormedUriString(link, UriKind.Absolute)) { // TODO: Extract } return link; } 无论哪种方式,如果他们做一个链接,它将只是us
public static string GetUsernameFromLink(string link)
{
if (Uri.IsWellFormedUriString(link, UriKind.Absolute))
{
// TODO: Extract
}
return link;
}
无论哪种方式,如果他们做一个链接,它将只是
username.website.com
。假设我输入https://adam.hello.com
我需要提取adam
这应该可以
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Test
{
public class Program
{
public static void Main(string[] args)
{
var text = "https://www.google.com"; // Sample input
Regex pattern = new Regex(@"[a-z]+(\.[a-z]+)+"); // Regular expression to match the domain
Match match = pattern.Match(text); // Finds matches
var domains = match.Value.Split('.'); // Get the match value and split it into an array.
Console.WriteLine(string.Join(":", domains)); // Sample output
}
}
}
这里发生的事情是,您声明一个Regex
实例,该实例捕获URL字符串的一部分,该部分与域名的典型模式相匹配,即
[any number of a-z Characters ] [ followed by any number of instances of a group of characters, that starts with DOT and followed by any number of a-z Characters]
捕获后,我将其拆分为一个字符串[]
,第0个索引正好包含我想要的内容
这种方法最好的地方是隐式验证输入字符串。但是,在某些情况下,Regex
可能会引入性能影响,这在您的情况下是不可能的。使用以下代码:
public static string GetUsernameFromLink(string link)
{
if (Uri.IsWellFormedUriString(link, UriKind.Absolute))
{
// TODO: Extract
Uri baseUri = new Uri(link);
var un = baseUri.Host.Split('.').First();
}
return link;
}
var regex = new Regex(@"\/\/(.+?)\.");
Match match = regex .Match(@"https://adam.hello.com");
if(match.Success)
Console.WriteLine(match.Groups[1]);
这段代码将写“adam”这是纯正则表达式,将URL与http、https或其他URL相匹配
public static string GetUrlPart(string url)
{
Regex regex = new Regex(@"(?:(?:http(s)?:\/\/)|^)(\w+)", RegexOptions.Compiled);
Match match = regex.Match(url);
return match.Success ? match.Groups[2].Value : string.Empty;
}
这个问题对我来说像是个骗局。也许是
Regex
+子字符串
解决方案?或者是一个Regex
+Split
解决方案?一个单一的谷歌搜索会给出大量的结果。域名总是一样的吗?例如“hello.com”?是的@maccettura是的。Uri=新的UriBuilder(someUrlString).Uri;如果在源字符串url中不存在,那么它默认为一个scheme,因此从那里解析出您需要的任何片段都是非常好的。BobK就快到了,所以我把它们的代码提高了。加上我在手机上,这是一个痛苦的原因,应用程序是垃圾。