如何在Java中的String.contains()方法中使用正则表达式 [英] How to use regex in String.contains() method in Java

查看:206
本文介绍了如何在Java中的String.contains()方法中使用正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查String是否按顺序包含单词stores,store和product。无论他们之间是什么。

I want to check if a String contains the words "stores", "store" and "product" in that order. No matter what is in between them.

我尝试使用 someString.contains(存储%store%product); 以及 .contains(store%store%product);

我是否需要明确声明一个正则表达式并在方法上传递它或者我根本无法传递正则表达式?

Do i need to explicitly declare a regex and pass it on the method or i can't pass a regex at all?

推荐答案

String.contains



String.contains 使用String,句点。它不适用于正则表达式。它将检查指定的确切字符串是否出现在当前字符串中。

String.contains

String.contains works with String, period. It doesn't work with regex. It will check whether the exact String specified appear in the current String or not.

请注意 String.contains 不检查单词边界;它只是检查子字符串。

Note that String.contains does not check for word boundary; it simply checks for substring.

正则表达式比字符串更强大.contains ,因为您可以对关键字(以及其他内容)强制执行单词边界。这意味着您可以将关键字搜索为 words ,而不仅仅是子串

Regex is more powerful than String.contains, since you can enforce word boundary on the keywords (among other things). This means you can search for the keywords as words, rather than just substrings.

使用 String.matches 使用以下正则表达式:

Use String.matches with the following regex:

"(?s).*\\bstores\\b.*\\bstore\\b.*\\bproduct\\b.*"

RAW正则表达式(删除字符串文字中的转义 - 这是你在打印上面的字符串时得到的结果):

The RAW regex (remove the escaping done in string literal - this is what you get when you print out the string above):

(?s).*\bstores\b.*\bstore\b.*\bproduct\b.*

\ b 检查字边界,这样你就不会获得恢复商店产品的匹配。请注意,商店3store_product 也被拒绝,因为数字和 _ 被认为是单词的一部分,但我怀疑这种情况出现在自然文本中。

The \b checks for word boundary, so that you don't get a match for restores store products. Note that stores 3store_product is also rejected, since digit and _ are considered part of a word, but I doubt this case appear in natural text.

由于双边都检查了单词边界,因此上面的正则表达式将搜索确切的单词。换句话说,商店商店与上面的正则表达式不匹配,因为你正在搜索单词 store 而不用 s

Since word boundary is checked for both sides, the regex above will search for exact words. In other words, stores stores product will not match the regex above, since you are searching for the word store without s.

通常匹配任何字符 许多新行字符。开头的(?s)使匹配任何字符,无异常(感谢Tim Pietzcker指出这一点) 。

. normally match any character except a number of new line characters. (?s) at the beginning makes . matches any character without exception (thanks to Tim Pietzcker for pointing this out).

这篇关于如何在Java中的String.contains()方法中使用正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆