使用正则表达式从EditText验证[Preference]文件名 [英] Validate [Preference] filename from EditText using regex
问题描述
[第一个应用]我为用户提供了使用不同的首选项文件来拥有多个配置文件的选项.用户可以自己命名其个人资料.我创建了一个自定义对话框,以将文件名作为edittext中的输入.有效的文件名应仅包含[A-Z,a-z,0-9,_,-].我让用户知道此限制.
[FIRST APP] I am providing users with an option to have multiple profiles using different preference files. The users can name their profiles themselves. I have made a custom dialog box to take filename as input in edittext. A valid filename should contains only [A-Z, a-z, 0-9, _, -]. I am letting the user know about this restriction.
每当用户输入一个无效字符时,我都希望将该字符从edittext中删除,最好显示一个祝酒词.经过简短的搜索,我相信可以使用正则表达式轻松完成此任务(与我在edittext上使用textwatcher的基于天真字符串的方法相比).但是,我以前从未使用过regex,因此需要帮助.
Whenever a user enters an invalid character, I want that character to be deleted from edittext and preferably display a toast. After a brief search I believe that this task can be performed easily using regular expressions (as compared to my naive string based approach using textwatcher on edittext). But, I have never worked with regex before and need help regarding this.
ps-一个值得关注的用例是,用户发疯并在edittext中键入随机字符.
ps - A concerning usecase is when the user goes berserk and types random character in edittext.
推荐答案
这是上述特定方案的工作代码,我们将textwatcher附加到我们的edittext上,然后使用模式(对huidube的感谢)来验证输入:>
Here is the working code for above specific scenario, we attach a textwatcher to our edittext and then verify the input using a pattern (Thnaks to huidube) :
profile_name.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) { }
@Override
public void afterTextChanged(Editable s) {
String str = s.toString();
if (!(str.matches("[a-zA-Z0-9-_ ]*"))) {
str = removeIllegalChar(str).trim(); //trim whitespaces
profile_name.setText(str);
profile_name.setSelection(str.length()); //use only if u want to set cursor to end
}
}
});
private String removeIllegalChar(String str) {
for (int i=0; i < str.length(); i++) {
if (!(String.valueOf(str.charAt(i)).matches("[a-zA-Z0-9-_ ]*"))) {
//as the callback is called for each character entered, we can return on first non-match
//maybe show a short toast
return str.substring(0, i) + str.substring(i+1);
}
}
return str;
}
我有两个测试设备,一个是垂死的退伍军人,另一个是Moto G,上面的过程在两个设备上都能顺利进行.因此,我认为这是可以接受的最佳选择.
I have two test devices, one a dying veteran and a Moto G and the above procedure works smoothly on both. So, I guess this is acceptably optimal.
这篇关于使用正则表达式从EditText验证[Preference]文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!