Можно ли редактировать текст с помощью Regex без цикла?
Например выполнить задачу с помощью Regex:
Текст на ввод: it (cap) was the best of TIMES (low)
Текст на вывод: It was the best of times
(cap) это у нас в роле Сapitalize,и суть задачи применить функцию на предыдущий элемент.
Я сделал задачу разделив вес текст через Split на отдельный элемент и поместиль на массив,и на каждый элемент применяль фукнцию через индекс пропустив через цикл весь массив.
Вопрос: Можно ли через Regex проделать все это без цикла и массива?
мой код:
package main
import (
"fmt"
"os"
"regexp"
"strconv"
"strings"
)
func main() {
args := os.Args[1:]
f := args[0]
file, err := os.ReadFile(f)
if err != nil {
panic(err)
}
split_sep := regexp.MustCompile(`\(.*?\)|\S*`)
Formatted_text := split_sep.FindAllString(string(file), -1)
for i := 0; i < len(Formatted_text); i++ {
cap := regexp.MustCompile(`\(cap\)`)
findCap := cap.MatchString(Formatted_text[i])
if findCap {
Formatted_text[i-1] = (strings.Title(Formatted_text[i-1]))
Formatted_text[i] = ""
}
low := regexp.MustCompile(`\(low\)`)
findLow := low.MatchString(Formatted_text[i])
if findLow {
Formatted_text[i-1] = (strings.ToLower(Formatted_text[i-1]))
Formatted_text[i] = ""
}
}
Ответы (1 шт):
Автор решения: Wiktor Stribiżew
→ Ссылка
Пример кода, которые решает проблему с использованием двух вызовов regexp.ReplaceAllStringFunc:
package main
import (
"fmt"
"regexp"
"strings"
)
func main() {
re_cap := regexp.MustCompile(`\S+\s+\(cap\)`)
re_low := regexp.MustCompile(`\S+\s+\(low\)`)
text := "it (cap) was the best of TIMES (low)"
fmt.Println(
re_cap.ReplaceAllStringFunc(
re_low.ReplaceAllStringFunc(text, func(m string) string {
return strings.ToLower(strings.Fields(m)[0])
}), func(n string) string {
return strings.Title(strings.Fields(n)[0])
}))
}
Результат:
It was the best of times