-2

I have the below regex, which currently allows '_' but not '-'.

string validCharacters = @"^\w+$";

Regex.Match(componentName, validCharacters);

But I want to also to include '-' as a valid character. The '-' can be at any place in the string. i,e: first,last,middle,after '_' etc.

Below are the few test cases:

"DTD_rtop-234"

"DTD-rtop_234"

"-DTD_rtop-234"

"DTD_rtop-234-"

"DTD_-rtop-234"

Any help will be much appreciated.

2
  • What you mean under "does not allow ''"_? Commented Mar 22, 2018 at 6:08
  • @SeM It means it allows [underscore] but not [hypen]. Commented Mar 22, 2018 at 6:28

1 Answer 1

2

Combine the - character with the \w characters in a single character class: [-\w].

Your desired regex is therefore: ^[-\w]+$.

Sign up to request clarification or add additional context in comments.

3 Comments

Perfect ! Clean, clear and brief
Use this solution and check on regex101.com
Thanks @Samantha . It's solved my purpose.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.