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

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

问题描述

我想检查一个字符串是否按顺序包含单词商店"、商店"和产品",无论它们之间是什么.

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(stores%store%product);.contains("stores%store%product");

我是否需要明确声明一个正则表达式并将其传递给方法,或者我可以根本不传递正则表达式?

Do I need to explicitly declare a regex and pass it on the method or can I not pass a regex at all?

推荐答案

String.contains

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

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.

Regex 比 String.contains 更强大,因为您可以对关键字(除其他外)强制执行字边界.这意味着您可以将关键字作为进行搜索,而不仅仅是子字符串.

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).*stores.*store.*product.*

 检查词边界,这样您就不会得到 restores store products 的匹配项.请注意,stores 3store_product 也被拒绝,因为 digit 和 _ 被认为是单词的一部分,但我怀疑这种情况是否出现在自然文本中.

The  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.

由于双方都检查了单词边界,因此上面的正则表达式将搜索准确的单词.换句话说,stores stores product 将与上面的正则表达式不匹配,因为您正在搜索没有 s 的词 store.

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.

. 通常匹配任何字符 except 一些换行符.开头的 (?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天全站免登陆