-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathStringExtensions.cs
87 lines (71 loc) · 2.5 KB
/
StringExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace AttributeRouting.Helpers
{
public static class StringExtensions
{
private static readonly Regex PathAndQueryRegex = new Regex(@"(?<path>[^\?]*)(?<query>\?.*)?");
public static string FormatWith(this string s, params object[] args)
{
return String.Format(s, args);
}
public static void GetPathAndQuery(this string url, out string path, out string query)
{
// NOTE: Do not lowercase the querystring vals
var match = PathAndQueryRegex.Match(url);
// Just covering my backside here in case the regex fails for some reason.
if (!match.Success)
{
path = url;
query = null;
}
else
{
path = match.Groups["path"].Value;
query = match.Groups["query"].Value;
}
}
public static bool HasValue(this string s)
{
return !String.IsNullOrWhiteSpace(s);
}
public static bool HasNoValue(this string s)
{
return String.IsNullOrWhiteSpace(s);
}
public static bool IsValidUrl(this string s, bool allowTokens = false)
{
var urlParts = s.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
var invalidUrlPatterns = new List<string>
{
@"[#%&:<>/{0}]".FormatWith(allowTokens ? null : @"\\\+\{\}?\*"),
@"\.\.",
@"\.$",
@"^ ",
@" $"
};
var invalidUrlPattern = String.Join("|", invalidUrlPatterns);
return !urlParts.Any(p => Regex.IsMatch(p, invalidUrlPattern));
}
public static string[] SplitAndTrim(this string s, params string[] separator)
{
if (!s.HasValue())
return null;
return s.Split(separator, StringSplitOptions.RemoveEmptyEntries).Select(i => i.Trim()).ToArray();
}
public static bool ValueEquals(this string s, string other)
{
if (s == null)
return other == null;
return s.Equals(other, StringComparison.OrdinalIgnoreCase);
}
public static string ValueOr(this string s, string otherValue)
{
if (s.HasValue())
return s;
return otherValue;
}
}
}