How to match hyphens with Regular Expression?

后端 未结 6 1117
[愿得一人]
[愿得一人] 2020-11-21 23:36

How to rewrite the [a-zA-Z0-9!$* \\t\\r\\n] pattern to match hyphen along with the existing characters ?

相关标签:
6条回答
  • 2020-11-21 23:36

    Is this what you are after?

    MatchCollection matches = Regex.Matches(mystring, "-");
    
    0 讨论(0)
  • 2020-11-21 23:48

    use "\p{Pd}" without quotes to match any type of hyphen. The '-' character is just one type of hyphen which also happens to be a special character in Regex.

    0 讨论(0)
  • 2020-11-21 23:52

    The hyphen is usually a normal character in regular expressions. Only if it’s in a character class and between two other characters does it take a special meaning.

    Thus:

    • [-] matches a hyphen.
    • [abc-] matches a, b, c or a hyphen.
    • [-abc] matches a, b, c or a hyphen.
    • [ab-d] matches a, b, c or d (only here the hyphen denotes a character range).
    0 讨论(0)
  • 2020-11-21 23:56

    Escape the hyphen.

    [a-zA-Z0-9!$* \t\r\n\-]
    

    UPDATE:
    Never mind this answer - you can add the hyphen to the group but you don't have to escape it. See Konrad Rudolph's answer instead which does a much better job of answering and explains why.

    0 讨论(0)
  • 2020-11-21 23:56

    [-a-z0-9]+,[a-z0-9-]+,[a-z-0-9]+ and also [a-z-0-9]+ all are same.The hyphen between two ranges considered as a symbol.And also [a-z0-9-+()]+ this regex allow hyphen.

    0 讨论(0)
  • 2020-11-21 23:57

    It’s less confusing to always use an escaped hyphen, so that it doesn't have to be positionally dependent. That’s a \- inside the bracketed character class.

    But there’s something else to consider. Some of those enumerated characters should possibly be written differently. In some circumstances, they definitely should.

    This comparison of regex flavors says that C♯ can use some of the simpler Unicode properties. If you’re dealing with Unicode, you should probably use the general category \p{L} for all possible letters, and maybe \p{Nd} for decimal numbers. Also, if you want to accomodate all that dash punctuation, not just HYPHEN-MINUS, you should use the \p{Pd} property. You might also want to write that sequence of whitespace characters simply as \s, assuming that’s not too general for you.

    All together, that works out to apattern of [\p{L}\p{Nd}\p{Pd}!$*] to match any one character from that set.

    I’d likely use that anyway, even if I didn’t plan on dealing with the full Unicode set, because it’s a good habit to get into, and because these things often grow beyond their original parameters. Now when you lift it to use in other code, it will still work correctly. If you hard‐code all the characters, it won’t.

    0 讨论(0)
提交回复
热议问题