java 没有任何空格的字母数字、连字符和下划线的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38265411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:16:17  来源:igfitidea点击:

Regular Expression for AlphaNumeric, Hyphen and Underscore without any space

javaregex

提问by Gautam R

I would like to have a regular expression that checks if the string contains Alphanumerics, Hyphen and Underscore. There should not be any spaces or other special characters other these three. My string will be under either of these 2 patterns.

我想要一个正则表达式来检查字符串是否包含字母数字、连字符和下划线。除了这三个之外,不应有任何空格或其他特殊字符。我的字符串将在这两种模式中的任何一种之下。

  • XYZ0123_123456
  • ABCdefGHI-727
  • XYZ0123_123456
  • ABCdefGHI-727

I have already tried this expression. But it didnt workout. [[a-zA-Z0-9_-]*]

我已经尝试过这种表达方式。但它没有锻炼。[[a-zA-Z0-9_-]*]

回答by abubaker

Working
Here is the quick solution.


在这里工作是快速解决方案。

String regex = "^[a-zA-Z0-9_-]*$";
sampleString.matches(regex);
  • (^) anchor means start of the string

  • ($) anchor means end of the string

  • A-Z , a-z represent range of characters

  • 0-9 represent range of digit

  • ( _ ) represent underscore

  • ( - ) represent hyphen

  • (^) 锚表示字符串的开始

  • ($) 锚表示字符串的结尾

  • AZ , az 代表字符范围

  • 0-9 代表数字范围

  • ( _ ) 代表下划线

  • ( - ) 代表连字符

回答by Thomas Ayoub

You can use ^[\w-]*$where \wmeans:

您可以使用^[\w-]*$where\w表示:

  • any letter in the range a-z, A-Z,
  • any digit from 0 to 9,
  • underscore
  • 范围内的任何字母a-z, A-Z,
  • 来自 的任何数字0 to 9
  • underscore


The error you made was to encapsulate you correct regex ([a-zA-Z0-9_-]*== [\w-]*) within a character class, loosing the quantifier (*) meaning

您犯的错误是将正确的正则表达式 ( [a-zA-Z0-9_-]*== [\w-]*)封装在字符类中,从而丢失了量词 ( *) 的含义