Regex: Match alphanumerical chars, underscores, hyphens and brackets

Regex: ^[a-zA-Z0-9_()-]*$

Test (Java, JUnit)

public class RegexTest extends TestCase {

public void testRegex(){

   String sRegex ="^[a-zA-Z0-9_()-]*$";
   assertEquals(true, "abc".matches(sRegex));
   assertEquals(true, "(abc)".matches(sRegex)); 
   assertEquals(true, "a(b)f".matches(sRegex));
   assertEquals(true, "abc_mh".matches(sRegex));
   assertEquals(true, "_asdf".matches(sRegex));
   assertEquals(true, "asdFasd_".matches(sRegex));
   assertEquals(true, "asd-Fasd_".matches(sRegex));
   assertEquals(true, "asd---Fasd_".matches(sRegex));
   assertEquals(true, "asd-__Fasd_".matches(sRegex));
   assertEquals(true, "_F".matches(sRegex));
   assertEquals(true, "_Fuu_".matches(sRegex));
   assertEquals(true, "_Fuu_".matches(sRegex));
   assertEquals(true, "83727429432712".matches(sRegex));
   assertEquals(true, "UsrXX".matches(sRegex));
   assertEquals(true, "Region2".matches(sRegex));

   assertEquals(false, "ab!c".matches(sRegex));
   assertEquals(false, "ab#c".matches(sRegex));
   assertEquals(false, "ab*c".matches(sRegex));
   assertEquals(false, "ab+c".matches(sRegex));
   assertEquals(false, "ab\"c".matches(sRegex));
   assertEquals(false, "ab'c".matches(sRegex));
}
}

Leave a Comment

comments powered by Disqus