简体   繁体   English

如何添加正则表达式以将字母数字字符与某些特殊字符匹配

[英]How to add regular expression to match alphanumeric character with some special characters

I have the words with special character like 我有一些特殊字符的单词,例如

Ex: ABC12-xy
    ABCD
    ABC12_12
    12-AB_xy

I have tried the following but not working 我已经尝试了以下方法,但无法正常工作

'(-\\w+)'   ,   '[-A-Za-z_0-9]'

But not working. 但是没有用。

Try this regex 试试这个正则表达式

[\w-]+

Which matches all below 符合以下所有条件

ABC12-xy
ABCD
ABC12_12
12-AB_xy

use [\\w-]+ to match the entire string. 使用[\\w-]+来匹配整个字符串。 You can use ^ and $ to specify the start and the end of the line. 您可以使用^$指定行的开始和结束。 For example ^[\\w-]+$ would match the entire line only if the line has all word or - characters. 例如, ^[\\w-]+$仅在该行包含所有单词或-字符的情况下才匹配整行。

String regex = "[A-Za-z0-9_\\-]+";
System.out.println(java.util.regex.Pattern.matches(regex, "ABC12-xy"));
System.out.println(java.util.regex.Pattern.matches(regex, "ABCD"));
System.out.println(java.util.regex.Pattern.matches(regex, "ABC12_12"));
System.out.println(java.util.regex.Pattern.matches(regex, "12-AB_xy"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM