-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy patheee-rich-regex.sh
executable file
·86 lines (78 loc) · 1.94 KB
/
eee-rich-regex.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env bash
echo eee-rich-regex: $@ >> /tmp/a.txt
echo end >> /tmp/a.txt
# Generate permutations for regexps joining
function generate_permutations {
local items=("$@")
local len=${#items[@]}
if (( len == 0 )); then
echo ""
return
elif (( len == 1 )); then
echo "(${items[0]})"
return
fi
local i j first remaining
for ((i=0; i<len; i++)); do
first="${items[i]}"
remaining=()
for ((j=0; j<len; j++)); do
if (( j != i )); then
remaining+=("${items[j]}")
fi
done
generate_permutations "${remaining[@]}" | while read -r rest; do
echo "(${first}).*${rest}"
done
done
}
# Main script
type="emacs"
regexps=()
# Parse arguments
while [[ $# -gt 0 ]]; do
case "$1" in
--type)
type="$2"
shift 2
;;
*)
regexps+=("$1")
shift
;;
esac
done
joined=""
case "$type" in
"pcre")
if (( ${#regexps[@]} > 1 )); then
printf -v joined "^%s" "$(printf "(?=.*%s)" "${regexps[@]}")"
else
joined="${regexps[0]}"
fi
;;
"basic")
if (( ${#regexps[@]} > 0 )); then
IFS=.\* joined="${regexps[*]}"
else
joined=""
fi
;;
*)
if (( ${#regexps[@]} > 3 )); then
ignored="${regexps[@]:3}"
echo "Too many regexps, ${ignored} ignored. Use post-filtering!" >&2
regexps=("${regexps[@]:0:3}")
fi
if (( ${#regexps[@]} > 0 )); then
permutations=$(generate_permutations "${regexps[@]}")
joined=$(echo "$permutations" | paste -sd '|' -)
# if [[ $type == "emacs" ]]; then
# joined=$(sed 's/(/\\(/g; s/)/\\)/g; s/|/\\|/g' <<< "$joined")
# fi
else
joined=""
fi
;;
esac
echo "$joined"