working on it ...

Filters

Explore Public Snippets

Sort by

Found 2,977 snippets matching: regex

    public by clsw  350039  0  6  1

    Image upload to API, return direct link. (IMGUR)

    Imgur, one of the best image hosts in the world, has a fantastic API, this is a VERY simple and usable implementation of it, just pass an image to the function and it will return the direct link to yout image, heavily commented and easy to use.
    public string UploadImage(Image img)
            {
                //get a dev key from api.imgur.com, anonymous usage (no user auth) only.
                string devkey = "YOUR_CLIENT_ID (e.g. abcde1f234567g8)";
    
                //define the WebClient we'll use to communicate with Imgur.
                WebClient w = new WebClient();
                
                //adds the Header to authorize this application with Imgur, must include a valid CLIENT_ID from 'devkey' above.
                w.Headers.Add("Authorization", "Client-ID " + devkey);
    
                System.Collections.Specialized.NameValueCollection Keys = new System.Collections.Specialized.NameValueCollection();
                try
                {
                    //Converts the image to a byte array so it can be turned into a string for upload.
                    using (MemoryStream stream = new MemoryStream())
                    {
                        img.Save(stream, ImageFormat.Png);
                        Keys.Add("image", Convert.ToBase64String(stream.ToArray()));
                    }
                    
                    //uploads the string-formatted-image and waits for the response.
                    byte[] responseArray = w.UploadValues("https://api.imgur.com/3/image", Keys);
                    dynamic result = Encoding.ASCII.GetString(responseArray);
    
                    //formats the (long and technical) result into just the direct image link.
                    Regex reg = new Regex("link\":\"(.*?)\""); Match match = reg.Match(result);
                    string url = match.ToString().Replace("link\":\"", "").Replace("\"", "").Replace("\\/", "/");
    
                    //returns the online address of the image.
                    return url;
                }
                catch (Exception s) { MessageBox.Show(s.Message); return "err"; }
            }

    public by pan  312663  0  7  4

    CSS Regex Selector Extension For jQuery

    Using this extension enables regular expresions css selectors in jQuery
    /**
     * CSS Regex Selector Extension For jQuery
     * 
     */
    jQuery.expr[':'].regex = function(elem, index, match) {
       var matchParams = match[3].split(','),
           validLabels = /^(data|css):/,
           attr = {
               method: matchParams[0].match(validLabels) ?
                   matchParams[0].split(':')[0] : 'attr',
               property: matchParams.shift().replace(validLabels,'')
           },
           regexFlags = 'ig',
           regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
       return regex.test(jQuery(elem)[attr.method](attr.property));
    }

    public by boxshadow  96683  1  3  1

    Function to Format Phone Number with RegEx and Coldfusion

    Function to Format Phone Number with RegEx and Coldfusion: formatPhone.cfc
    <cfscript>
         component output="false" {
    
            public formatPhone function init(){
                    return this;
                    }
    
    	public string function formatPhone(required string phoneNumber)
    		description="Strips out anything that isn't a number and then takes the first 10 digits and formats them to our spec: (404) 555-1212"
    		output="false" 
    		{
    			var failedReturn = 0;
    			// Strip out everything but the numbers
    			var cleanNumber = REReplaceNoCase(arguments.phoneNumber,"[^0-9]","","All");
    			
    			// area code can't start with a 1 or 0, so remove them if they are at the beginning
    			do{
    				if(Left(cleanNumber,1) EQ 1 OR Left(cleanNumber,1) EQ 0){
    					cleanNumber = right(cleanNumber,len(cleanNumber) - 1);
    				}
    			}
    			while(left(cleanNumber,1) EQ 1 OR left(cleanNumber,1) EQ 0);
    			
    			// If there are stil 10 or more digits left, lets use the left 10 and drop the rest
    			if(len(cleanNumber) LT 10){
    				return failedReturn;
    			}
    			else{
    				cleanNumber = left(cleanNumber,10);
    			}
    			// Format the 10 digits we have
    			cleanNumber = "(#left(cleanNumber,3)#) #mid(cleanNumber,4,3)#-#right(cleanNumber,4)#";
    			return cleanNumber;		
    		}
         }
    </cfscript>
    
    

    public by mfurlend  2460  1  5  0

    REGEX: find: isset($_GET['something']) ... replace: array_key_exists('something',$_GET)

    Replace isset() with array_key_exists()
    find : isset\(\$_(GET|SET|REQUEST) ?\[ ?['"](\w*)['"] ?\]\)
    replace: array_key_exists('$2', '$1')            

    public by viveklucky1848  2443  2  6  0

    Life-saver regex to remove desired html tags completely with their contents

    Remove html tags with their contents, useful when you want to remove certain frequently occurring tags from page, for designer to set design with css. (eg. label tag)
    Find: <label.*?>(.|\s)*?</label>
    Replace with: ''(nothing :) not even quotes)
    
    
    Dare to try below example with my devilish remover;)
    
    <label class="email" for="email">
    	<span>New Email</span>
    	<p>New email 2</p>
    	NEW EMAIL3
    </label>                                    

    public by lbottaro  4513  5  7  5

    How to sort a Javascript array parsing elements using regex pattern

    The Javascript Array.sort() method accepts a callback function to compare two elements of the array using a specific logic. The callback function below may help you in sorting an array matching a particular regular expression pattern. The format of elements in array is x/y/z, where x, y and z are integers, eg "5/10/2". I need to sort the eleme
    var myCompare = function(a,b) {
    	var matchPattern_A = /^([0-9]+)\/([0-9]+)\/([0-9]+)$/g.exec(a);
    	var matchPattern_B = /^([0-9]+)\/([0-9]+)\/([0-9]+)$/g.exec(b);
    
    	if(matchPattern_A && matchPattern_B)
    	{
    		//Apply regex sort
    		//I need to sort based on match[1], match[2], match[3]
    		console.log('Apply regex sort');
    
    		if (parseInt(matchPattern_A[1], 10) < parseInt(matchPattern_B[1], 10))
    			return -1;
    		if (parseInt(matchPattern_A[1], 10) > parseInt(matchPattern_B[1], 10))
    			return 1;
    		else {
    			if (parseInt(matchPattern_A[2], 10) < parseInt(matchPattern_B[2], 10))
    				return -1;
    			if (parseInt(matchPattern_A[2], 10) > parseInt(matchPattern_B[2], 10))
    				return 1;
    			else {
    				if (parseInt(matchPattern_A[3], 10) < parseInt(matchPattern_B[3], 10))
    					return -1;
    				if (parseInt(matchPattern_A[3], 10) > parseInt(matchPattern_B[3], 10))
    					return 1;
    				return 0;
    			}
    		}
    	}
    	else {
    		//Apply basic lexicographic sort
    		console.log('Apply basic lexicographic sort');
    		if (a < b)
    			return -1;
    		if (a > b)
    			return 1;
    		return 0;
    	}
    };
    
    var myArr = [ '5/4/30', '5/10/2', '5/4/3', '1/3/8'];
    console.log(myArr);
    myArr.sort(this.myCompare);
    console.log(myArr);
    
    /*  Example,
        having an array as
        ['5/4/30', '5/10/2', '5/4/3', '1/3/8']
        it will be sorted as
        ['1/3/8', '5/4/3', '5/4/30', '5/10/2']
    */            

    public by cghersi  3283  2  8  0

    C#: How to dinamically check a string and its length using a Regex

    Thsi method creates a Regex by replacing a placeholder as minimum and maximum length (e.g. in case of username and / or password verifiers...). It can be extended also to apply different Regex with respect to some particular business logic.
    static private string s_nameRegEx = @"^[_a-zA-Z][_a-zA-Z0-9-. ]{ç,§}$"; //'ç' is a placeholder for actual minimum length, '§' is a placeholder for actual maximum length
            
    public static bool NameIsValid(string candidateName, int minimumLen, bool checkOnlyLen, int maxLen = int.MaxValue)
    {
        if (candidateName == null)
            return (minimumLen == 0); //return false if there's a minimum len
        string trimmedName = candidateName.Trim();
        if ((trimmedName.Length < minimumLen) || (trimmedName.Length > maxLen))
            return false;
        if (checkOnlyLen)
            return true;
        Regex nameExpr = new Regex(s_nameRegEx.Replace("ç", (minimumLen - 1) + "").Replace("§", (maxLen - 1) + ""));
        return nameExpr.IsMatch(trimmedName);
    }
    

    public by cghersi  7238  16  9  1

    C#: Replace an exact word in a sentence

    Same as String.Replace but with case-insensitive matches and search for the exact word. E.g. searching in "Java and Javascript with Java." the word 'Java', and replacing it with 'Python' results in "Python and Javascript with Python."
    public static string ReplaceExactWord(this string stringToSearch, string find, string replace)
    {
        string pattern = @"\b" + find + @"\b";
        return Regex.Replace(stringToSearch, pattern, replace, RegexOptions.IgnoreCase);
    }
    

    public by lbottaro  3412  2  7  1

    Regular Expression In Python - Simple Grouping

    This python code shows how to define a regular expression path and have it applied to some string. The regex is defined using the compile built-in method of re library. In the following example some groups are used to parse information from filename strings listed by 'ls' linux command. Exception will raise if no match will be found.
    import os, re
    
    # Assume to have some file names listed
    # The matching path is: <id>_<name>_<code>.txt
    
    # Define regex 
    my_regExp = re.compile(r'(?P<id>^[^_]*)_(?P<name>[^.]*)_(?P<code>[^.]*).txt')
    
    for myFile in os.popen('ls -F /some/path').readlines():
        id= ''
        name= ''
        code= ''
        try:
               id= my_regExp.match(myFile).group('id')
        except:
               msgErr='Error on id - ' + myFile
        try:
               name= my_regExp.match(myFile).group('name')
        except:
               msgErr='Error on name - ' + myFile
        try:
               code= my_regExp.match(myFile).group('code')
        except:
               msgErr='Error on code- ' + myFile
    
            

    public by micurs  2824  1  7  0

    Find all Internal Links

    Regular expression that find all links that start with the sites domain, a slash, relative file path, or a hashtag. This regex can be used to find all the internal links in a page or section of a page.
    var siteURL = "http://" + top.location.host.toString();
    
    var $internalLinks = $("a[href^='"
             + siteURL
             + "'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']");
    • Public Snippets
    • Channels Snippets