利用正则表达式匹配数据库内容

功能

正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。

具体:拿到quesion的标签,用|分割,在数据库用正则去查,返回有相近标签的question

使用

mysql正则表达式

MySQL中使用 REGEXP 操作符来进行正则表达式匹配。

p1|p2|p3 匹配 p1 或 p2 或 p3。例如,‘z|food’ 能匹配 “z” 或 “food”。’(z|f)ood’ 则匹配 “zood” 或 “food”。

 //根据正则的方式匹配 标签
    @Select("select * from question where id!=#{id} and tag REGEXP #{tag}")
    List<Question> selectRelated(Question question);

questionServiceImpl

 public List<QuestionDTO> selectRelated(QuestionDTO queryDTO) {
        if (queryDTO.getTag()==null){
            return new ArrayList<>();
        }
        //将queryDTO的tag用,分割再用|拼装
        String[] tags= StringUtils.split(queryDTO.getTag(),",");
        String regexpTag= Arrays.stream(tags).collect(Collectors.joining("|"));
        Question question = new Question();
        question.setId(queryDTO.getId());
        question.setTag(regexpTag);

        List<Question> questions = questionMapper.selectRelated(question);
        List<QuestionDTO> questionDTOS = questions.stream().map(q -> {
            QuestionDTO questionDTO = new QuestionDTO();
            BeanUtils.copyProperties(q, questionDTO);
            return questionDTO;
        }).collect(Collectors.toList());
        return questionDTOS;
    }
}

菜鸟教程文档

mysql正则表达式
正则表达式

发布了14 篇原创文章 · 获赞 0 · 访问量 43

猜你喜欢

转载自blog.csdn.net/weixin_43559860/article/details/104955194