为什么我必须在Java正则表达式中指定整个字符串? [英] Why I must specify whole string in Java regular expression?
问题描述
假设我有一个字符串:
String str = "some strange string with searched symbol";
我想在其中搜索一些符号,假设它将是字符串
。所以我们有以下内容:
And I want to search in it some symbols, suppose it will be "string"
. So we have a following:
str.matches("string"); //false
str.matches(".*string.*"); //true
因此,正如标题中所述,为什么我必须指定整个字符串Java正则表达式?
So, as stated in the title, why I must specify whole string in Java regular expression?
Java文档说:
public boolean matches(String regex)
public boolean matches(String regex)
判断此字符串是否与给定的正则表达式匹配。
Tells whether or not this string matches the given regular expression.
它没有说
判断此整个字符串是否与给定的正则表达式匹配。
Tells whether or not this whole string matches the given regular expression.
例如,在 php
它将是:
$str = "some strange string with searched symbol";
var_dump(preg_match('/string/', $str)); // int(1)
var_dump(preg_match('/.*string.*/', $str)); //int(1)
因此,两个正则表达式都是 true
。
我认为这是正确的,因为如果我想测试整个字符串我会做 str.matches(^ string $) ;
So, both of the regex's will be true
.
And I think this is correct, because if I want to test whole string I would do str.matches("^string$");
PS:是的,我知道这是搜索子串,更简单,更快捷的是使用 str.indexOf(string)
或 str.contains(string)
。我的问题只涉及Java正则表达式。
PS: Yes, I know that is to search a substring, simpler and faster will be to use str.indexOf("string")
or str.contains("string")
. My question regards only to Java regular expression.
UPDATE :正如@ ChrisJester所述 - Young(和@GyroGearless)解决方案之一,如果你想搜索 regex
这是一个主题字符串的一部分,就是使用 find()
这样的方法:
UPDATE: As stated by @ChrisJester-Young (and @GyroGearless) one of the solutions, if you want to search regex
that is part of a subject string, is to use find()
method like this:
String str = "some strange string with searched symbol";
Matcher m = Pattern.compile("string").matcher(str);
System.out.println(m.find()); //true
推荐答案
匹配
始终匹配整个输入字符串。如果要允许子字符串匹配,请使用 find
。
matches
always matches the whole input string. If you want to allow substrings to match, use find
.
这篇关于为什么我必须在Java正则表达式中指定整个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!