Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 检查字符串是否包含另一个完整字符串_Java_Regex_String - Fatal编程技术网

Java 检查字符串是否包含另一个完整字符串

Java 检查字符串是否包含另一个完整字符串,java,regex,string,Java,Regex,String,所以,我一直在尝试在线查找是否有一种方法可以让一个字符串在java中搜索另一个完整的字符串。不幸的是,我还没有找到任何有效的方法 我的意思是: String str = "this is a test"; 如果我搜索这是,它应该返回true。但是如果我搜索这个I它应该是假的 我尝试过使用String.matches(),但这不起作用,因为正在搜索的某些字符串中可能包含[,],?,等等,这会使它失效。使用String.indexOf(搜索)!=-1也不起作用,因为它将为部分单词返回true。在正

所以,我一直在尝试在线查找是否有一种方法可以让一个字符串在java中搜索另一个完整的字符串。不幸的是,我还没有找到任何有效的方法

我的意思是:

String str = "this is a test";
如果我搜索
这是
,它应该返回
true
。但是如果我搜索
这个I
它应该是假的


我尝试过使用
String.matches()
,但这不起作用,因为正在搜索的某些字符串中可能包含[,],?,等等,这会使它失效。使用
String.indexOf(搜索)!=-1也不起作用,因为它将为部分单词返回true。

在正则表达式中使用零宽度单词边界分隔符
\b

String str = "this is a test";
String search = "this is";
Pattern p = Pattern.compile(String.format("\\b%s\\b", Pattern.quote(search)));
boolean matches = p.matcher(Pattern.quote(str)).find();

如果您还将单词与非字母字符分开,而不仅仅是空格,则可以使用机制。也许这样试试

String str = "[this] is...";
String search = "[this] is";

Pattern p = Pattern.compile("(?!<\\p{IsAlphabetic})"
        + Pattern.quote(search) + "(?!\\p{IsAlphabetic})");
boolean matches = p.matcher(str).find();
String str=“[this]是…”;
字符串搜索=“[this]是”;

模式p=Pattern.compile((?)不起作用。使用
String.matches(.*?\\b“+search+“\\b*”);
不会拾取类似“[test]”的内容。当然会。你只需要先使用。啊,是的-应该使用
Matcher\find()
而不是
\matches()
。当搜索类似
String str=“[this]的字符串时。。。“;
当我搜索
[这]是
得到它-我要做的就是做
p.matcher(Pattern.quote(str)).find();
让它正确地找到里面的符号。它完全按照我需要的方式工作。谢谢你!@IAreKyleW00t没问题:)