如何检查字符串中是否只有选定的字符?

发布于 2024-10-07 10:11:35 字数 274 浏览 1 评论 0原文

检查字符串是否仅包含以下字符的最佳和最简单的方法是什么:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_

我想要一个像这样的伪代码的示例:

//If String contains other characters
else
//if string contains only those letters

请并谢谢:)

What's the best and easiest way to check if a string only contains the following characters:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_

I want like an example like this pseudo-code:

//If String contains other characters
else
//if string contains only those letters

Please and thanks :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

枫林﹌晚霞¤ 2024-10-14 10:11:35
if (string.matches("^[a-zA-Z0-9_]+$")) {
  // contains only listed chars
} else {
  // contains other chars
}
if (string.matches("^[a-zA-Z0-9_]+$")) {
  // contains only listed chars
} else {
  // contains other chars
}
只是偏爱你 2024-10-14 10:11:35

对于该特定类别的字符串,请使用正则表达式“\w+”。

Pattern p = Pattern.compile("\\w+");
Matcher m = Pattern.matcher(str);

if(m.matches()) {} 
else {};

请注意,我使用 Pattern 对象来编译正则表达式一次,这样就不必再次编译它,如果您要多次或在循环中进行此检查,这可能会很好。根据java文档...

如果一个模式要多次使用
次,编译一次并重复使用
它会比
每次都会调用这个方法。

For that particular class of String use the regular expression "\w+".

Pattern p = Pattern.compile("\\w+");
Matcher m = Pattern.matcher(str);

if(m.matches()) {} 
else {};

Note that I use the Pattern object to compile the regex once so that it never has to be compiled again which may be nice if you are doing this check in a-lot or in a loop. As per the java docs...

If a pattern is to be used multiple
times, compiling it once and reusing
it will be more efficient than
invoking this method each time.

留一抹残留的笑 2024-10-14 10:11:35

轮到我了:

static final Pattern bad = Pattern.compile("\\W|^$");
//...
if (bad.matcher(suspect).find()) {
  // String contains other characters
} else {
  // string contains only those letters
}

上面搜索单个不匹配或空字符串。

并根据 JavaDoc for Pattern

\w  A word character: [a-zA-Z_0-9]
\W  A non-word character: [^\w]

My turn:

static final Pattern bad = Pattern.compile("\\W|^$");
//...
if (bad.matcher(suspect).find()) {
  // String contains other characters
} else {
  // string contains only those letters
}

Above searches for single not matching or empty string.

And according to JavaDoc for Pattern:

\w  A word character: [a-zA-Z_0-9]
\W  A non-word character: [^\w]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文