Created
August 10, 2012 21:46
-
-
Save 5342/3318303 to your computer and use it in GitHub Desktop.
Simple URI parsing in SQL with Regex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Data; | |
using System.Data.SqlClient; | |
using System.Data.SqlTypes; | |
using Microsoft.SqlServer.Server; | |
using System.Text.RegularExpressions; | |
public partial class UserDefinedFunctions | |
{ | |
/// <summary> | |
/// Parses a single parameter value from a full URI | |
/// </summary> | |
/// <param name="uri">Ful URI</param> | |
/// <param name="pram">Parameter to search for</param> | |
/// <returns></returns> | |
[Microsoft.SqlServer.Server.SqlFunction] | |
public static SqlString ParseQueryString(SqlString uri, SqlString param) | |
{ | |
// Regex.Escape, "Escapes a minimal set of characters (\, *, +, ?, |, {, [, (,), ^, $,., #, and white space)" | |
// If someone other then yourself is going to use this you may want to add some better user input validation | |
var escapedParam = Regex.Escape(param.ToString().Substring(0, Math.Min(param.ToString().Length, 20))); | |
Regex r = new Regex("[&\\?]" + escapedParam + "=(?<value>[^&]*)&?"); | |
var match = r.Match(uri.ToString()); | |
return new SqlString(Uri.UnescapeDataString(match.Groups["value"].Value)); | |
} | |
/// <summary> | |
/// Removes anything past a ?, =, &, or ; from a full URI | |
/// </summary> | |
/// <param name="uri">Ful URI</param> | |
/// <returns></returns> | |
[Microsoft.SqlServer.Server.SqlFunction] | |
public static SqlString GetFulPath(SqlString uri) | |
{ | |
Regex r = new Regex("^(?<value>[^?=&;]*)"); | |
var match = r.Match(uri.ToString()); | |
return new SqlString(Uri.UnescapeDataString(match.Groups["value"].Value)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment