正则表达式的有效文本

时间:2011-12-02 13:21:12

标签: c# regex

我试图创建一个验证!!

的正则表达式
  1. 如果文本只有特殊字符或空格,则应验证false ...
  2. Ex:@#$ ##

    1. 如果最后有一些文字和特殊字符,则应返回true ...
    2. EX:测试!!

      1. 如果它是以空格或特殊字符开头的。它应该验证为false。
      2. Ex:@#Test

        1. 如果特殊字符(空格或昏迷除外)介于两者之间。它应该验证为false !!
        2. Ex:te#$ sT

          我道歉,对于这个复杂的正则表达式,我的知识不允许我输入我尝试的任何代码。因为我除了[a-b A-B !@#$%^&*()]

          之外什么都没有

          更新

          1. 使用Fischermaen的答案进行测试 - ^(\ s | \ w)\ w * \ W * $
          2. sdf SDF!:验证为false

            _ __ :验证为真(在得分下)

            sadf,sdfsdf :验证为false

            空格:验证为真

3 个答案:

答案 0 :(得分:3)

试试这个:

foundMatch = Regex.IsMatch(subjectString, @"^(?!\W*$)(?=[ .\w]\w*\W*$).*$");

我试图弄明白你的意思让我很头疼。你必须学会​​更好地表达自己。

<强>解释

"
^            # Assert position at the beginning of the string
(?!          # Assert that it is impossible to match the regex below starting at this position (negative lookahead)
   \W        # Match a single character that is a “non-word character”
      *      # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   $         # Assert position at the end of the string (or before the line break at the end of the string, if any)
)
(?=          # Assert that the regex below can be matched, starting at this position (positive lookahead)
   [ .\w]    # Match a single character present in the list below
             # One of the characters “ .”
             # A word character (letters, digits, etc.)
   \w        # Match a single character that is a “word character” (letters, digits, etc.)
      *      # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   \W        # Match a single character that is a “non-word character”
      *      # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   $         # Assert position at the end of the string (or before the line break at the end of the string, if any)
)
.            # Match any single character that is not a line break character
   *         # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$            # Assert position at the end of the string (or before the line break at the end of the string, if any)
"

答案 1 :(得分:1)

以下是我的建议:

^(\s|\w)\w*\W*$

<强>解释

^(\s|\w) the first character has to be a whitespace or a alphanumeric (including underscore)

\w*      followed by any number of alphanumeric (including underscore)

\W*$     at the end of the string any number of any *except* alphanumeric characters are allowed.

答案 2 :(得分:1)

据我所知,你只想接受包含一些字母然后是一些特殊字符的字符串。所以像这样:

[(a-zA-Z)+(\!\@\#\$\%\^\&\*\(\))+]