Java DOT 的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3862479/
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
regular expression for DOT
提问by John
What is the regular expression for . and .. ?
的正则表达式是什么?和 .. ?
if(key.matches(".")) {
do something
}
The matches accepts String which asks for regular expression. Now i need to remove all DOT's inside my MAP.
匹配接受要求正则表达式的字符串。现在我需要删除我的 MAP 中的所有 DOT。
采纳答案by mikej
. matches any character so needs escaping i.e. \.
, or \\.
within a Java string (because \
itself has special meaning within Java strings.)
. 匹配任何需要转义的字符 ie \.
,或\\.
在 Java 字符串中(因为\
它本身在 Java 字符串中具有特殊含义。)
You can then use \.\.
or \.{2}
to match exactly 2 dots.
然后,您可以使用\.\.
或\.{2}
来精确匹配 2 个点。
回答by Noon Silk
...
...
[.]{1}
or
或者
[.]{2}
?
?
回答by Sachin Shanbhag
[+*?.] Most special characters have no meaning inside the square brackets. This expression matches any of +, *, ? or the dot.
[+*?.] 大多数特殊字符在方括号内没有意义。此表达式匹配 +、*、? 或点。
回答by Margus
Use String.Replace()
if you just want to replace the dots from string. Alternative would be to use Pattern-Matcher
with StringBuilder
, this gives you more flexibility as you can find groups that are between dots. If using the latter, i would recommend that you ignore empty entries with "\\.+"
.
使用String.Replace()
,如果你只是想从字符串替换点。另一种方法是使用Pattern-Matcher
with StringBuilder
,这为您提供了更大的灵活性,因为您可以找到点之间的组。如果使用后者,我建议您忽略带有"\\.+"
.
public static int count(String str, String regex) {
int i = 0;
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while (m.find()) {
m.group();
i++;
}
return i;
}
public static void main(String[] args) {
int i = 0, j = 0, k = 0;
String str = "-.-..-...-.-.--..-k....k...k..k.k-.-";
// this will just remove dots
System.out.println(str.replaceAll("\.", ""));
// this will just remove sequences of ".." dots
System.out.println(str.replaceAll("\.{2}", ""));
// this will just remove sequences of dots, and gets
// multiple of dots as 1
System.out.println(str.replaceAll("\.+", ""));
/* for this to be more obvious, consider following */
System.out.println(count(str, "\."));
System.out.println(count(str, "\.{2}"));
System.out.println(count(str, "\.+"));
}
The output will be:
输出将是:
--------kkkkk--
-.--.-.-.---kk.kk.k-.-
--------kkkkk--
21
7
11
回答by fylex
You should use contains not matches
您应该使用包含不匹配
if(nom.contains("."))
System.out.println("OK");
else
System.out.println("Bad");