由于某种原因,我无法获得"preference_network_"的模式匹配,后面跟着任何其他内容作为单个字符串。我希望能够使用key.matches()方法测试首选项键是否包含"preference_network_"。我怎样才能让它工作,我已经尝试了一些事情,但没有成功。谢谢你的预付。
很抱歉没有说清楚。所有这些解决方案我都能执行并且知道。我要做的就是使用"钥匙"。函数,其中key是onSharedPreferenceChangeListener方法的参数。这就是我在工作中遇到的困难。
我知道我不一定要用这个,我可以用开头。我只是想知道。
谢谢
解决方案:
str.startsWith("preference_network_");
str.contains("preference_network_");
与模式// the same as contains.
Pattern p = Pattern.compile("preference_network_");
p.matcher(str).find();
// the same as startsWith.
Pattern p = Pattern.compile("^preference_network_");
p.matcher(str).find();
如果你想使用matches()
,你必须写完整的模式:
Pattern p = Pattern.compile("^preference_network_.*");
p.matcher(str).matches();
因为match的执行就好像你的模式以^开始,以$结束,即
Pattern.compile("^something$").matcher(str).find()
与Pattern.compile("something").matcher(str).matches()
相同
无regex:
boolean matches = myString.startsWith("preference_network_");