如何验证字符串是英语? [英] How do I verify that a string is in English?

查看:94
本文介绍了如何验证字符串是英语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从控制台读取一个字符串。如何确保它只包含英文字符和数字?

I read a string from the console. How do I make sure it only contains English characters and digits?

推荐答案

假设通过英文字符 26个字符的拉丁字母表,这将是一个使用正则表达式的区域: ^ [a-zA-Z0-9] * $

Assuming that by "English characters" you are simply referring to the 26-character Latin alphabet, this would be an area where I would use regular expressions: ^[a-zA-Z0-9 ]*$

例如:

if( Regex.IsMatch(Console.ReadLine(), "^[a-zA-Z0-9]*$") )
{ /* your code */ }

在这种情况下,正则表达式的好处是,你真正关心的是一个字符串是否匹配一个模式 - 这是一个正则表达式奇妙地工作。它清楚地捕捉到你的意图,如果你定义的英文字符扩展超过26个字母的话,它很容易扩展。

The benefit of regular expressions in this case is that all you really care about is whether or not a string matches a pattern - this is one where regular expressions work wonderfully. It clearly captures your intent, and it's easy to extend if you definition of "English characters" expands beyond just the 26 alphabetic ones.

有一个体面的这里有一系列的文章,介绍有关正则表达式的更多信息。

There's a decent series of articles here that teach more about regular expressions.

JørnSchou-Rode的回答提供了一个很好的解释,说明这里提供的正则表达式如何匹配您的输入。

Jørn Schou-Rode's answer provides a great explanation of how the regular expression presented here works to match your input.

这篇关于如何验证字符串是英语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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