【发布时间】:2023-03-28 09:35:01
【问题描述】:
当然,我可以编写正则表达式来处理这两种情况,例如regexp.Compile("[a-zA-Z]"),但我的正则表达式是由用户给出的字符串构造的:
reg, err := regexp.Compile(strings.Replace(s.Name, " ", "[ \\._-]", -1))
其中s.Name 是名称。这可能类似于“西北偏北”。现在,对我来说最明显的解决方案是遍历s.Name 的每个字符并为每个字母写下'[nN]':
for i := 0; i < len(s.Name); i++ {
if s.Name[i] == " " {
fmt.Fprintf(str, "%s[ \\._-]", str);
} else {
fmt.Fprintf(str, "%s[%s%s]", str, strings.ToLower(s.Name[i]), strings.ToUpper(s.Name[i]))
}
}
但我觉得这是一个相当不优雅的解决方案。速度不是问题,但我需要知道是否有其他方法。
【问题讨论】: