tags:

views:

62

answers:

4

Hi,

I need to regex string myString to only have:

  • 0-9
  • A-Z or a-z
  • any of these characters '!#$%&'*+-/=?^_`{|}~.

This is my code line:

new Regex("[a-zA-Z0-9]").IsMatch(myString);

So far I have [a-zA-Z0-9] and this works fine for the first two listitems. Currently tearing my hair out (and it's so nice I want to keep it) over metacharacters and getting nowhere.

Any help would be greatly appreciated. Thanks. Dave

+3  A: 
"[a-zA-Z0-9'!#$%&'*+/=?^_`{|}~.-]"

check that ("-") minus sign be the last char in a [] sequence

zed_0xff
A: 

Meta characters are fine between brackets, as long as you escape the significant ones. Moreover the dash MUST be the last one of your sequence.

new Regex("[a-zA-Z0-9'!#$%&'*+/=?^_`{|}~-]").IsMatch(myString);
Palantir
Nope. The . alllows any character so that doesn't work either.
Dave
+1  A: 

Try:

var re = "[a-zA-Z0-9" +  Regex.Escape("'!#$%&'*+-/=?^_`{|}~.") + "]";
leppie
`Regex.Escape` isn't safe in a character class - it doesn't escape `-` : http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx . It will also escape characters that don't need it, but that's OK.
Kobi
+1  A: 

Hi there If you want only the listed characters in your string it is very simple.but you need to match beginning an end of line

new Regex("^[a-zA-Z0-9'!#$%&'*+/=?^_`{|}~.-]*$").IsMatch(myString);
josephj1989