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

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

问题描述

我读从控制台的字符串。我如何确保它仅包含英文字符和数字?

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.

有一个像样的series这里文章,教更多的正则表达式。

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

约恩休乌 - 罗德的回答提供了这里介绍的正则表达式是如何工作的,以配合您输入一个很好的解释。

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天全站免登陆