Regular expression group capture

foreword

Colleagues complained that the data given by the backend was beyond imagination, and they needed to process the strings by themselves, which was a bit troublesome to write normally. It's time for regularity!

need

converts the string 1-5|08:00:00-18:00:00to周一至周五 08:00-18:00

operate

introduce

Ordinary regular matching is not repeated here. Regex has a practical thing called group capture. In fact, it takes ()a packet of regular expressions and transforms it into a group. Some people have rivers and lakes, and there are groups, there are group numbers. The group number is automatically assigned, and the group can be referenced by the group number (this is very important).

write

We need to divide the original string into 4 groups, match 1, 5, 08:00 and 18:00 respectively so that we can get the data we want. Numbers are easy to match \d. Special characters such as -and |are used .to match. In terms of time, use it lazily \d. The final grouping is written as follows:

/(\d).(\d).([\d]{2}:[\d]{2})(?:.[\d]{2}).([\d]{2}:[\d]{2})(?:.[\d]{2})/gi

It seems that there are ()not only four groups wrapped, in fact, there are two groups at the beginning that ?:means not to participate in the capture, that is, the group number will not be assigned

quote

The default group number starts from 1. In JS, use $1, $2... to refer to the content matched by the group:

    const str = "1-5|08:00:00-18:00:00";
    const reg = /(\d).(\d).([\d]{2}:[\d]{2})(?:.[\d]{2}).([\d]{2}:[\d]{2})(?:.[\d]{2})/gi;
    const result = str.replace(reg, "周$1至周$2 $3-$4");
    console.log(result);  // 周1至周5 08:00-18:00

For further processing, replace 1 and 5 with the corresponding week. The second parameter of replace can be a function, and referring to the regular matching result in the function requires another way, similar toRegExp.$1

	const str = "1-5|08:00:00-18:00:00";
    const reg = /(\d).(\d).([\d]{2}:[\d]{2})(?:.[\d]{2}).([\d]{2}:[\d]{2})(?:.[\d]{2})/gi;
    const weekList = ["日", "一", "二", "三", "四", "五", "六"];
    const res = str.replace(reg, () => {
    
    
      return `${
      
      weekList[RegExp.$1]}至周${
      
      weekList[RegExp.$2]} ${
      
      RegExp.$3}-${
      
      
        RegExp.$4
      }`;
    });
    console.log(res); // 周一至周五 08:00-18:00

that's all!

Guess you like

Origin blog.csdn.net/weixin_54858833/article/details/126830400