如何区分正则表达式第 m 个捕获组的第 n 个匹配模式与 bash 中较早或较晚的匹配?

How can I distinguish the n-th matched pattern of the m-th capture group of a regular expression from earlier or later matches in bash?

此问题与可由 bash 处理的正则表达式有关。

我有一个正则表达式,它在文本中找到所有匹配日期的符号 d.m.yyyy 或 dd.m.yyyy 或 d.mm.yyyy 或 dd.mm.yyyy 如果它恰好在制表符或至少两个空格之间:

(?<=\t|\s{2,})(\d{1,2}\.\d{1,2}\.\d{4})(?=\t|\s{2,})

我如何替换这个的所有发现(让我们首先假设)根据 ISO 8601 格式化的日期捕获组,即在符号 yyyy-mm-dd?

由于分隔制表符或至少两个空格处于环视状态,因此它们不属于我的捕获组。它们将保留在原始字符串中。

问题分解为:

1.如何处理 $1

的第 n 个匹配项

2。在这种情况下,如何重新排列由点分隔的三个组件?

如果你想用bash处理它,请你试试下面的方法:

#!/bin/bash

str=$'foo\t27.6.2021  bar'                      # example of the input line
pat=$'^(.*)(\t| {2,})([0-9]{1,2})\.([0-9]{1,2})\.([0-9]{4})(\t| {2,})(.*)$'
if [[ $str =~ $pat ]]; then
    a=("${BASH_REMATCH[@]:1}")                  # assign array "a" to the matched substrings excluding "${BASH_REMATCH[0]}" (entire match)
    y=${a[4]}; a[4]=${a[2]}; a[2]=$y;           # swap year and date
    printf "%s%s%04d-%02d-%02d%s%s\n" "${a[@]}" # print the formatted result
fi

如评论所述,bash 正则表达式不支持环视。您需要将整行捕获为子字符串并重新使用它们。