Here is my code
这是我的代码
public class regMatch {
public static void main(String... args)
{
String s = "1";
System.out.println(s.contains("/[0-9]/"));
}
}
Its printing false;
它的印刷错误;
I want to use regular expression in contains
method.
我想在包含方法中使用正则表达式。
How can I use it.
我怎么用它呢?
4 个解决方案
#1
6
I want to use regular expression in contains method.
我想在包含方法中使用正则表达式。
How can I use it
我如何使用它?
you can not use regex in contains
method
您不能在包含方法中使用regex。
#2
3
You don't need (and shouldn't use) delimiters in a Java regex
在Java regex中不需要(也不应该使用)分隔符。
And the contains()
method doesn't support regexes. You need a regex object:
contains()方法不支持regex。你需要一个regex对象:
Pattern regex = Pattern.compile("[0-9]");
Matcher regexMatcher = regex.matcher(s);
System.out.println(regexMatcher.find());
#3
1
You can use the Pattern class to test for regex matches. However, if you are just testing for the presence of digits in the string, directly testing for this would be more efficient than using a regex.
您可以使用Pattern类来测试regex匹配。但是,如果您只是测试字符串中的数字是否存在,那么直接测试它将比使用regex更有效。
#4
1
You can use matches()
with the regex .*[0-9].*
to find if there is any digit:
您可以使用与regex .*[0-9]的匹配()。*查找是否有任何数字:
System.out.println(s.matches(".*[0-9].*"));
(or for multiline strings, use the regex (.|\\s)*[0-9](.|\\s)*
instead)
(或者对于多行字符串,使用regex (.|\\s)*[0-9](.|\ s)*代替)
An alternative - if you are eager to use contains()
is iterate all chars from 0 to 9, and check for each if the string contains it:
另一种方法——如果您渴望使用contains(),则将所有字符从0迭代到9,并检查字符串是否包含:
boolean flag = false;
for (int i = 0; i < 10; i++)
flag |= s.contains("" + i);
System.out.println(flag);
#1
6
I want to use regular expression in contains method.
我想在包含方法中使用正则表达式。
How can I use it
我如何使用它?
you can not use regex in contains
method
您不能在包含方法中使用regex。
#2
3
You don't need (and shouldn't use) delimiters in a Java regex
在Java regex中不需要(也不应该使用)分隔符。
And the contains()
method doesn't support regexes. You need a regex object:
contains()方法不支持regex。你需要一个regex对象:
Pattern regex = Pattern.compile("[0-9]");
Matcher regexMatcher = regex.matcher(s);
System.out.println(regexMatcher.find());
#3
1
You can use the Pattern class to test for regex matches. However, if you are just testing for the presence of digits in the string, directly testing for this would be more efficient than using a regex.
您可以使用Pattern类来测试regex匹配。但是,如果您只是测试字符串中的数字是否存在,那么直接测试它将比使用regex更有效。
#4
1
You can use matches()
with the regex .*[0-9].*
to find if there is any digit:
您可以使用与regex .*[0-9]的匹配()。*查找是否有任何数字:
System.out.println(s.matches(".*[0-9].*"));
(or for multiline strings, use the regex (.|\\s)*[0-9](.|\\s)*
instead)
(或者对于多行字符串,使用regex (.|\\s)*[0-9](.|\ s)*代替)
An alternative - if you are eager to use contains()
is iterate all chars from 0 to 9, and check for each if the string contains it:
另一种方法——如果您渴望使用contains(),则将所有字符从0迭代到9,并检查字符串是否包含:
boolean flag = false;
for (int i = 0; i < 10; i++)
flag |= s.contains("" + i);
System.out.println(flag);