[英]How to find substring of a string with whitespaces in Java?
我想检查字符串是否包含特定的子字符串,并为其使用CONTAINS()。
但是这里的问题是空间。
Ex-str1 =“ c not in(5,6)”
我想检查str是否包含NOT IN,所以我正在使用str.contains(“ not in”)。
但是问题在于,NOT和IN之间的空间不确定,即也可以有5个空间。
如何解决我可以找到子字符串而不喜欢之间没有空格的问题...
使用正则表达式 ( Pattern
)获取Matcher
来匹配您的字符串。
regexp应该为"not\\\\s+in"
(“ not”,后跟多个空格字符,后跟“ in”):
public static void main(String[] args) {
Matcher m = Pattern.compile("not\\s+in").matcher("c not in(5,6)");
if (m.find())
System.out.println("matches");
}
请注意,有一个名为matches(String regexp)
的String方法。 您可以使用正则表达式".*not\\\\s+in.*"
来获取匹配项,但这并不是执行模式匹配的好方法。
您应该使用正则表达式 : "not\\\\s+in"
String s = "c not in(5,6)";
Matcher matcher = Pattern.compile("not\\s+in").matcher(s);
System.out.println(matcher.find());
说明: \\\\s+
表示任何类型的空格[也可以接受制表符],并且必须重复至少一个[将接受任何大于等于= 1的数字]。
如果只需要空格而没有制表符,则将正则表达式更改为"not +in"
使用String.matches()
方法,该方法检查字符串是否与正则表达式( docs )匹配。
在您的情况下:
String str1 = "c not in(5,6)";
if (str1.matches(".*not\\s+in.*")) {
// do something
// the string contains "not in"
}
不区分大小写:( (?i)
将换行符视为点.
也是:( (?s)
str1.matches("(?is).*not\\s+in.*")
请尝试以下,
int result = str1.indexOf ( "not in" );
if ( result != -1 )
{
// It contains "not in"
}
else if ( result == -1 )
{
// It does not contain "not in"
}
通常,您可以执行以下操作:
if (string.indexOf("substring") > -1)... //It's there
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.