0

I need to create reg-ex for path like aaaa/bbb/ccc or aaa-bbb or aaa_bbb_ccc_ddd etc How should I do that ? It can contain only alpha numeric with hyphen underscore and slash. Ive tried something like this which is not working

@"^((?:/[a-zA-Z0-9]+)+/?|/?(?:[a-zA-Z0-9]+/)+)[a-zA-Z0-9]*$"
Jean Tehhe
  • 1,087
  • 2
  • 17
  • 33

2 Answers2

1

If you don't mind if your path has mixed delimiters like aaa-bbb/ccc then you can get it done in one go reasonably easily with:

"^(?:[A-z0-9]+[-_\/]?)*$"

This will accept aaa-bbb/ccc, and aaa/ but reject aaa--bbb. If you want to ensure that you have only one type of delimiter, then we can create one repeated block for each delimiter type:

"^(?:(?:[A-z0-9]+-?)*|(?:[A-z0-9]+_?)*|(?:[A-z0-9]+\/?)*)$"

This will still tolerate trailing delimiters, which you can get rid of that by adding another group to the end:

"^(?:(?:[A-z0-9]+-?)*|(?:[A-z0-9]+_?)*|(?:[A-z0-9]+\/?)*)[A-z0-9]+$"

If you want allow leading delimiters, just move them before the group. Also notice the extra \s* to allow trailing whitespace.

"^(?:(?:-?[A-z0-9]+)*|(?:_?[A-z0-9]+)*|(?:\/?[A-z0-9]+?)*)\s*$"

Not exactly easy on the eyes, but it does work (in perl at least).

Jon Betts
  • 2,443
  • 9
  • 12
  • Thanks Jon ,voted up! I use the last regex you provided. there is two little thing,how can I add that user can start with the symbols like /aaaa/bbbb or -aaa-bbb-ccc. and how should ignore the spacess at the end for example if user type value with and at the end add space he got errors... – Jean Tehhe May 01 '14 at 11:56
  • There you go, I've updated the answer to include the extra details. – Jon Betts May 01 '14 at 12:24
1

Try this one to match words

\b[a-zA-Z0-9]*[-/_]+[a-zA-Z0-9]+\b

enter image description here


Note:

  • \w include underscore also that why I have used [a-zA-Z0-9]
  • remove \b from either end if you don't want to match word boundary

Pattern expatiation:

\w     A word character: [a-zA-Z_0-9]
\b     A word boundary
[abc]  a, b, or c (simple class)
Braj
  • 44,339
  • 5
  • 51
  • 69