简体   繁体   English

如何在java中编写和使用正则表达式

[英]How to write and use regular expression in java

I want to write a regular expression in java which will accept the String having alphabets, numbers, - and space any number of times any where. 我想在java中编写一个正则表达式,它将接受具有字母,数字, - 和空格的字符串。

The string should only contain above mentioned and no other special characters. 该字符串应仅包含上述内容而不包含其他特殊字符。 How to code the regular expression in java? 如何在java中编写正则表达式?

I tried the following, It works when I run it as a java application. 我尝试了以下内容,当我将其作为java应用程序运行时,它可以工作。

But the same code when I run in web application and accept the values through XML, It accepts '/'. 但是当我在Web应用程序中运行并通过XML接受值时,它接受相同的代码,它接受'/'。

 String test1 = null;

 Scanner scan = new Scanner(System.in);
 test1 = scan.nextLine();

 String alphaExp = "^[a-zA-Z0-9-]*$";

 Pattern r = Pattern.compile(alphaExp);
 Matcher m = r.matcher(test1);

 boolean flag = m.lookingAt();

 System.out.println(flag);

Can anyone help me on this please? 有人可以帮我吗?

You can try to use POSIX character classes (see here ): 您可以尝试使用POSIX字符类(请参阅此处 ):

Pattern p = Pattern.compile("^[\\p{Alnum}\\p{Space}-]*$");
Matcher m = p.matcher("asfsdf 1212sdfsd-gf121sdg5 4s");
boolean b = m.lookingAt();

With this regular expression if the string you pass contain anything else than alphanumeric or space characters it will be a no match result. 使用此正则表达式,如果您传递的字符串包含除字母数字或空格字符以外的任何内容,则它将是不匹配的结果。

I think you're just missing a space from the character class - since you mentioned it in your text ^[a-zA-Z0-9 -]*$ 我想你只是错过了角色类的空间 - 因为你在文中提到它^[a-zA-Z0-9 -]*$

You can add the Pattern.MULTILINE flag too so you can specify how the pattern handles the lines: 您也可以添加Pattern.MULTILINE标志,以便指定模式处理线条的方式:

     String alphaExp = "^[a-zA-Z0-9 -]*$";

     Pattern r = Pattern.compile(alphaExp, Pattern.MULTILINE);
     Matcher m = r.matcher(test1);

     boolean flag = m.lookingAt();

Pay attention to the fact that * quantifier will make it match to everything including no matches (0 or more times, like empty lines or blank tokens "" , infinitely. 请注意*量词将使其与所有内容匹配,包括无匹配(0次或更多次,如空行或空白令牌"" ,无限期。

If you instead use + " [\\w\\d\\s-\\]+ " it will match one or more (consider using \\\\ for each \\ in your Java Regex code as follow: " [\\\\w\\\\d\\\\s-]+ " 如果您使用+ [\\w\\d\\s-\\]+它将匹配一个或多个(考虑在Java Regex代码中为每个\\使用\\\\ ,如下所示:“ [\\\\w\\\\d\\\\s-]+

Consider that * is a quantity operator that works as {0, } and + works like {1, } 考虑*是一个数量运算符,其作用为{0, }+作用类似于{1, }

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

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