• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

普通防爆pression检查,如果字符串包含指定的字符

用户头像
it1352
帮助1

问题说明

我如何检查,如果一个字符串包含的使用常规的前pressions指定的字符?

How do I check if a string contains only specified characters using regular expressions?

例1:检查是否字符串包含的字母和/或数字:

Example 1: Check if string contains only letters and/or numbers:

我的尝试:

Regex rgx = new Regex("[^A-Za-z0-9]");
string s = "This is a string.";

if (rgx.IsMatch(s))
 {
   // true
 }
 else
 {
   // false;
 }

这上面的例子应该返回false(因为我不想让段),但它返回true。

This above example should return false (because I don't want to allow periods), but it is returning true.

例2:只有字母和/或和/或空格和/或括号允许

Example 2: Only letters and/or numbers and/or spaces and/or parenthesis are allowed:

Regex rgx = new Regex("[^A-Za-z0-9() ]");
string s = "This is a [string].";

if (rgx.IsMatch(s))
 {
   // true
 }
 else
 {
   // false;
 }

此外,第二个例子应该返回false(因为我不想让支架或周期),但它返回true。

Again, the second example should return false (because I don't want to allow brackets or periods), but it is returning true.

正确答案

#1

您正则表达式是不正确。你检查什么

Your regex is incorrect. What you're checking for

Regex rgx = new Regex("[^A-Za-z0-9]");

将匹配任何的的性格是不是ASCII大写或小写字母或十进制数字等。如果你想检查一个字符串包含的完全的字母和数字,你可以说:

will match any single character that is other than an ASCII upper- or lower-case letter or decimal digit. If you want to check that a string consists solely of letters and numbers, you can say:

Regex rx = new Regex("^[A-Za-z0-9] $");

以上定期EX pression将匹配起始行的锚( ^ ),后面跟一个字母或数字( [A-ZA-Z0-9] )重复1次或多次( ),其次是行结束的锚(< $ C C $> $ )。

The above regular expression will match the start-of-line anchor (^), followed by a letter or digit ( [A-Za-z0-9]) repeated 1 or more times ( ), followed by the end-of-line anchor ($).

应该注意的是空格和标点符号算:在你原来的例子,测试字符串匹配一个第一个字符发现不是一个大写或小写字母或十进制数字,则SP(空格)字符抵消其他 4。

One should note that spaces and punctuation count: in your original example, the test string will match one the first character found other than an upper- or lower-case letter or decimal digit, the SP (space) character at offset 4.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfijeg
系列文章
更多 icon
同类精品
更多 icon
继续加载