Skip to content

Instantly share code, notes, and snippets.

@syed-ahmad
Forked from nikanos/RegExTest.cs
Created November 19, 2021 14:49
Show Gist options
  • Save syed-ahmad/edf02b0bc7854b0bc08e10ca8dc31914 to your computer and use it in GitHub Desktop.
Save syed-ahmad/edf02b0bc7854b0bc08e10ca8dc31914 to your computer and use it in GitHub Desktop.
RegEx - Do not allow leading and trailing whitespace
^(?!\s)[\s\S]+(?<!\s)$
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace RegExTest
{
static class MyExtensions
{
public static void PrintMatch(this Regex re, string input)
{
Console.WriteLine($"Math result <{input}> : {re.IsMatch(input)}");
}
}
class Program
{
static void Main(string[] args)
{
const string RE = @"^(?!\s)[\s\S]+(?<!\s)$";
Regex re = new Regex(RE);
var inputs = new List<string>
{
"test",
" test",
" test ",
"test ",
"test with space",
"test with space\n and new line",
"тест with χαρακτήρες på olika språk"
};
Console.WriteLine($"RE = {re.ToString()}");
inputs.ForEach(x => re.PrintMatch(x));
}
/* Output:
* RE = ^(?!\s)[\s\S]+(?<!\s)$
* Math result <test> : True
* Math result < test> : False
* Math result < test > : False
* Math result <test > : False
* Math result <test with space> : True
* Math result <test with space
* and new line> : True
* Math result <тест with χαρακτήρες på olika språk> : True
*/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment