方法匹配不好用 [英] method matches not work well

查看:117
本文介绍了方法匹配不好用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么这个正则表达式的方法返回false;

I don't understand why with this regex the method returns false;

Pattern.matches("\\bi", "an is");

我在字边界的字符!

推荐答案

在Java中,匹配尝试将模式与整个字符串匹配

In Java, matches attempts to match a pattern against the entire string.

String.matches Pattern.matches Matcher.matches

如果你想检查一个字符串中是否有匹配,你可以使用。* \。* 。在这种情况下,作为Java字符串文字,它是。* \\\\。*

If you want to check if there's a match somewhere in a string, you can use .*\bi.*. In this case, as a Java string literal, it's ".*\\bi.*".

这里使用的点是一个正则表达式元字符,意思是(几乎)任何字符。 * 是一个正则表达式元字符,表示零次或多次重复。因此,例如 A. * B 匹配 A ,后跟零或更多任意字符,然后是 B 参见rubular.com )。

As used here, the dot . is a regex metacharacter that means (almost) any character. * is a regex metacharacter that means "zero-or-more repetition of". So for example something like A.*B matches A, followed by zero-or-more of "any" character, followed by B (see on rubular.com).

  • regular-expressions.info/Repetition with Star and Plus and The Dot Matches (Almost) Any Character
  • Difference between .*? and .* for regex

请注意 * (以及其他元字符)可能会失去其特殊含义,具体取决于它们的应用位置耳。 [。*] 是一个字符类,它与文字句点或文字星号 * 。在反斜杠之前也会转义元字符,因此 a \\\。b 匹配ab

Note that both the . and * (as well as other metacharacters) may lose their special meaning depending on where they appear. [.*] is a character class that matches either a literal period . or a literal asterisk *. Preceded by a backslash also escapes metacharacters, so a\.b matches "a.b".

  • regular-expressions.info/Character Class and Literal Characters and Metacharacters

Java没有正则表达式基于 endsWith startsWith 和< a href =http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/lang/String.html#contains%28java.lang.Cha rSequence%29rel =nofollow noreferrer> 包含 。您仍然可以使用匹配来完成以下相同的操作:

Java does not have regex-based endsWith, startsWith, and contains. You can still use matches to accomplish the same things as follows:


  • matches(。* pattern。*) - 它是否包含 pattern 的匹配?

  • 匹配(pattern。*) - 是否以模式的匹配开头?

  • 匹配(。* pattern) - 是否以模式的匹配结束?

  • matches(".*pattern.*") - does it contain a match of the pattern anywhere?
  • matches("pattern.*") - does it start with a match of the pattern?
  • matches(".*pattern") - does it end with a match of the pattern?

这是一个快速备忘单,列出哪些方法是基于正则表达式的,哪些不是:

Here's a quick cheat sheet that lists which methods are regex-based and which aren't:

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