Java正则表达式匹配器不工作
我正在努力掌握图案和匹配器的窍门。这个方法应该使用regex模式来迭代一个州首府数组,并返回对应于该模式的一个或多个州。当我检查整个字符串,如“tallahassee”或“盐湖城”,但不检查“^t”之类的字符串时,该方法工作正常。我没有得到什么 这是调用它的方法和main:Java正则表达式匹配器不工作,java,regex,matcher,Java,Regex,Matcher,我正在努力掌握图案和匹配器的窍门。这个方法应该使用regex模式来迭代一个州首府数组,并返回对应于该模式的一个或多个州。当我检查整个字符串,如“tallahassee”或“盐湖城”,但不检查“^t”之类的字符串时,该方法工作正常。我没有得到什么 这是调用它的方法和main: public ArrayList<String> getState(String s) throws RemoteException { Pattern pattern = Pattern.compil
public ArrayList<String> getState(String s) throws RemoteException
{
Pattern pattern = Pattern.compile(s);
Matcher matcher;
int i=0;
System.out.println(s);
for(String ct:capitalValues)
{
matcher = pattern.matcher(ct);
if(ct.toLowerCase().matches(s))
states.add(stateValues[i]);
i++;
}
return states;
}
public static void main (String[] args) throws RemoteException
{
ArrayList<String> result = new ArrayList<String>();
hashTester ht = new hashTester();
result = ht.getState(("^t").toLowerCase());
System.out.println("result: ");
for(String s:result)
System.out.println(s);
}
public ArrayList getState(字符串s)引发RemoteException
{
Pattern=Pattern.compile;
匹配器匹配器;
int i=0;
系统输出打印项次;
for(字符串ct:大写值)
{
匹配器=模式匹配器(ct);
如果(ct.toLowerCase().匹配)
添加(stateValues[i]);
i++;
}
返回状态;
}
公共静态void main(字符串[]args)引发RemoteException
{
ArrayList结果=新建ArrayList();
hashTester ht=新的hashTester();
结果=ht.getState((“^t”).toLowerCase();
System.out.println(“结果:”);
for(字符串s:结果)
系统输出打印项次;
}
感谢您的帮助您甚至没有使用
匹配器
进行匹配。您正在使用String#matches()
方法。该方法和Matcher#matches()
方法都根据完整字符串匹配正则表达式,而不是其中的一部分。所以你的正则表达式应该覆盖整个字符串。如果只想匹配字符串的一部分,请使用Matcher\find()
方法
您应该这样使用它:
if(matcher.find(ct.toLowerCase())) {
// Found regex pattern
}
顺便说一句,如果您只想查看字符串是否以
t
开头,可以直接使用string#startsWith()
方法。这种情况下不需要正则表达式。但我想这是一个一般情况。^
是正则表达式中的一个字符。如果你不想锚定,你就必须逃离它。否则,^t
mens在字符串的开头添加t。使用\^t
对其进行转义感谢您指出这一点,我看了很多示例,但无法正确设置模式和匹配器语法。这完全有道理,因为我现在可以成功地应用它。再次感谢。