普通防爆pression检查,如果字符串包含指定的字符
问题说明
我如何检查,如果一个字符串包含的仅使用常规的前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.
正确答案
您正则表达式是不正确。你检查什么
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
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20