如何从 json 中提取正则表达式以解析短信 (android)
how to Extract regex from json to parse sms (android)
最近我从我的雇主那里得到了一个新项目。他向我提供了一个 Json 文件,其中包含 24k 行 Json 包含大量正则表达式,用于识别不同类型的短信。我的目标是使用文件中的正则表达式并使用相应的正则表达式检测 android phone 中的短信。
我不知道如何在我的 android 项目中使用每个正则表达式
基本上我想要的是确定 android phone 中的消息是否与我的 Json 文件中的正则表达式匹配。如果它匹配,那么它应该 return 该对象的其他字段。
如果有人能帮助我,我将不胜感激。
真的很简单。从 json 文件中的 "patterns" 生成一个 JSONArray。
当你已经做到这一点时,你只需要遍历数组中的每个对象并从 "regex".
中获取你的正则表达式
使用 Pattern 和 Matcher 根据正则表达式检查字段。
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(my_string);
if (matcher.find()) {
// you found a match
}
之后就可以随心所欲了
为清楚起见编辑:
if (!my_json_object_from_file.isNull("rules")) {
JSONArray rules_array = my_json_object_from_file.getJSONArray("rules");
for (JSONObject rule_object : rules_array) {
if (!rule_object.isNull("name")) {
// you have a name for the rule
}
if (!rule_object.isNull("patterns")) {
// you have some patterns
JSONArray pattern_array = rule_object.getJSONArray("patterns");
for (JSONObject pattern_object : pattern_array) {
// these are your pattern objects
if (!pattern_object.isNull("regex")) {
String regex = pattern_object.getString("regex");
// do work with the regex
}
}
}
}
}
最近我从我的雇主那里得到了一个新项目。他向我提供了一个 Json 文件,其中包含 24k 行 Json 包含大量正则表达式,用于识别不同类型的短信。我的目标是使用文件中的正则表达式并使用相应的正则表达式检测 android phone 中的短信。
我不知道如何在我的 android 项目中使用每个正则表达式
基本上我想要的是确定 android phone 中的消息是否与我的 Json 文件中的正则表达式匹配。如果它匹配,那么它应该 return 该对象的其他字段。
如果有人能帮助我,我将不胜感激。
真的很简单。从 json 文件中的 "patterns" 生成一个 JSONArray。
当你已经做到这一点时,你只需要遍历数组中的每个对象并从 "regex".
中获取你的正则表达式使用 Pattern 和 Matcher 根据正则表达式检查字段。
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(my_string);
if (matcher.find()) {
// you found a match
}
之后就可以随心所欲了
为清楚起见编辑:
if (!my_json_object_from_file.isNull("rules")) {
JSONArray rules_array = my_json_object_from_file.getJSONArray("rules");
for (JSONObject rule_object : rules_array) {
if (!rule_object.isNull("name")) {
// you have a name for the rule
}
if (!rule_object.isNull("patterns")) {
// you have some patterns
JSONArray pattern_array = rule_object.getJSONArray("patterns");
for (JSONObject pattern_object : pattern_array) {
// these are your pattern objects
if (!pattern_object.isNull("regex")) {
String regex = pattern_object.getString("regex");
// do work with the regex
}
}
}
}
}