[英]Looking for advices for regex
I'm trying to create a regex which has to match these patterns: \\n 700000000123
我正在尝试创建一个必须匹配以下模式的正则表达式: \\n 700000000123
I mean this "\\n"+"white space"+"12 digits"
我的意思是这个"\\n"+"white space"+"12 digits"
So I tried: 所以我尝试了:
(\\\\\\\\)(n)(\\\\s)(\\\\d{12})
or something like this: 或类似这样的东西:
(\\\\\\\\)(n)(\\\\s)(\\\\[0-9]{12})
But it still doesn't work. 但这仍然行不通。 for me {12} means repeat a digit \\d
or [0-9]
, 12 times ? 对我来说{12}表示重复数字\\d
或[0-9]
12次?
My idea is a java code which could check if a string contains this regex: 我的想法是一个Java代码,它可以检查字符串是否包含此正则表达式:
Boolean result = false;
String string_to_match = "a random string \n 700000000123"
String re1="(\\\\)";
String re2="(n)";
String re3="(\\s)";
String re4="([0-9]{11})";
Pattern p = Pattern.compile(re1+re2+re3+re4, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
if (string_to_match.contains(p.toString()){
result = true;
}
I tried to use: http://www.txt2re.com/ to help me. 我尝试使用: http : //www.txt2re.com/来帮助我。
Have you any advices to build this regex ? 您对构建此正则表达式有任何建议吗? I would like to understand why at the moment it doesn't work. 我想了解一下为什么现在不起作用。
You need to use String#matches
instead of String#contains
to match a regex. 您需要使用String#matches
而不是String#contains
来匹配正则表达式。
Following should work: 以下应该工作:
String re1="(\\n)";
String re2="( )";
String re3="(\\d{12})";
Pattern p = Pattern.compile(re1+re2+re3, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
System.out.println("\n 700000000123".matches(p.pattern())); // true
Or simply: 或者简单地:
System.out.println( "\n 700000000123".matches("(\n)( )(\\d{12})") ); // true
You can wrap it up in a chain of invocations without compromising to matching the entire input. 您可以将它包装成一连串的调用,而不会影响整个输入的匹配。
For instance: 例如:
String input = "\n 700000000123";
System.out.println(Pattern.compile("\n\\s\\d{12}").matcher(input).find());
Output 输出量
true
^\\\\n\\s+\\d{12}$
I guess this should work for you.See demo. 我想这应该适合您。请参阅演示。
https://regex101.com/r/eZ0yP4/33 https://regex101.com/r/eZ0yP4/33
\\n will work only in Unix machines. \\ n仅适用于Unix计算机。 In Windows it is \\r\\n. 在Windows中为\\ r \\ n。 Please use System.getProperty("line.separator") if you want your code to work both in linux and windows. 如果您希望代码在linux和Windows中都可以使用,请使用System.getProperty(“ line.separator”)。
Use the following 使用以下
System.out.println(Pattern.compile(System.getProperty("line.separator")+"\\s\\d{12}").matcher(input).find()); System.out.println(Pattern.compile(System.getProperty(“ line.separator”)+“ \\ s \\ d {12}”)。matcher(input).find());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.