Skip to content

Instantly share code, notes, and snippets.

@nikanos
Last active November 23, 2021 08:09
Show Gist options
  • Save nikanos/ad9e04295e3ac656b27ec8638fe1dba7 to your computer and use it in GitHub Desktop.
Save nikanos/ad9e04295e3ac656b27ec8638fe1dba7 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
*/
}
}
@syed-ahmad
Copy link

Thanks @nikanos , that was super handy!

@nikanos
Copy link
Author

nikanos commented Nov 23, 2021

Glad you found this useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment