当正则表达式不匹配时,如何允许我的程序继续?

时间:2017-03-31 08:16:29

标签: regex rust

我想使用regex crate并从字符串中捕获数字。

let input = "abcd123efg";
let re = Regex::new(r"([0-9]+)").unwrap();
let cap = re.captures(e).unwrap().get(1).unwrap().as_str();
println!("{}", cap);

如果input中存在数字,则会有效,但如果input中的数字不存在,则会出现以下错误:

thread 'main' panicked at 'called `Option::unwrap()` on a `None` value'

如果正则表达式不匹配,我希望我的程序继续。我该如何处理这个错误?

2 个答案:

答案 0 :(得分:8)

你可能想(重新)阅读the chapter on "Error Handling" in the Rust book。 Rust中的错误处理主要通过Result<T, E>Option<T>类型完成,两者都表示T类型的可选值,Result<T, E>包含有关缺少主值的其他信息。

您在遇到的每个unwrap()Option致电Resultunwrap()是一种方法:&#34;如果没有类型T的值,则让程序爆炸(恐慌)&#34;。 You only want to call unwrap() if an absence of a value is not expected and thus would be a bug!(注意:实际上,第二行中的unwrap()是完全合理的使用!)

但您错误地使用了unwrap()两次:captures()的结果和get(1)的结果。让我们先解决captures();它会返回Option<_>the docs say

  

如果未找到匹配项,则返回None

在大多数情况下,预期输入字符串与正则表达式不匹配,因此我们应该处理它。我们 match Option get(1)(处理这些可能错误的标准方法,请参阅Rust书籍章节)我们可以使用Regex::is_match()之前,检查字符串是否匹配。

接下来:i。同样,the docs tell us

  

返回与索引i处的捕获组关联的匹配项。如果None与捕获组不对应,或者捕获组未参与匹配,则会返回([0-9]+)

但这一次,我们不必处理这个问题。为什么?我们的正则表达式(None)是常量,我们知道捕获组存在并包含整个正则表达式。因此,我们可以排除导致unwrap()的两种可能情况。这意味着我们可以let input = "abcd123efg"; let re = Regex::new(r"([0-9]+)").unwrap(); match re.captures(e) { Some(caps) => { let cap = caps.get(1).unwrap().as_str(); println!("{}", cap); } None => { // The regex did not match. Deal with it here! } } ,因为我们不会期望缺少价值。

生成的代码可能如下所示:

 try{
            final String inFileName ="Your backup file here location path";
            File dbFile = new File(inFileName);
            FileInputStream fis = new FileInputStream(dbFile);
            String outFileName ="your app db location path";

            // Open the empty db as the output stream
            OutputStream output = new FileOutputStream(outFileName);

            // Transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            // Close the streams
            output.flush();
            output.close();
            fis.close();
            BackupRestore.this.runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(getApplicationContext(),"Restore Success",Toast.LENGTH_SHORT).show();
                }
            });

            alert();
        }catch (Exception e){
            e.printStackTrace();
        }

答案 1 :(得分:1)

您可以使用is_match查看,也可以只使用captures(e)的返回类型进行检查(它是Option<Captures<'t>>),而不是使用匹配来解开它。 (参见this如何处理选项)