【华为机试071】字符串通配符

题目描述:

在计算机中,通配符一种特殊语法,广泛应用于文件搜索、数据库、正则表达式等领域。现要求各位实现字符串通配符的算法。 要求: 实现如下2个通配符: *:匹配0个或以上的字符(字符由英文字母和数字0-9组成,不区分大小写。下同) ?:匹配1个字符

输入: 通配符表达式; 一组字符串。

输出: 返回匹配的结果,正确输出true,错误输出false

Java实现:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String reg = sc.nextLine();
            String str = sc.nextLine();

            reg = reg.replace("?", "[0-9a-zA-Z]{1}");
            reg = reg.replace("*", "[0-9a-zA-Z]*");
            System.out.println(str.matches(reg));
        }
    }
}

知识点:

    String的matches函数调用了Pattern.matches 其源码为 public static boolean matches(String regex, CharSequence input) { Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); return m.matches(); }
经验分享 程序员 微信小程序 职场和发展