普通防爆pression检查,如果字符串中包含指定的字符 [英] Regular Expression to check if string contains specified characters

查看:135
本文介绍了普通防爆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.

这篇关于普通防爆pression检查,如果字符串中包含指定的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆