简体   繁体   中英

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. 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.

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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