ParseKeywords 提取表达式中的关键词
(exp string)
| 141 | |
| 142 | // ParseKeywords 提取表达式中的关键词 |
| 143 | func (this *Regexp) ParseKeywords(exp string) (keywords []string) { |
| 144 | if len(exp) == 0 { |
| 145 | return nil |
| 146 | } |
| 147 | |
| 148 | reg, err := syntax.Parse(exp, syntax.Perl) |
| 149 | if err != nil { |
| 150 | return nil |
| 151 | } |
| 152 | |
| 153 | if len(reg.Sub) == 0 { |
| 154 | var keywordRunes = this.parseKeyword(reg.String()) |
| 155 | if len(keywordRunes) > 0 { |
| 156 | keywords = append(keywords, string(keywordRunes)) |
| 157 | } |
| 158 | return |
| 159 | } |
| 160 | if len(reg.Sub) == 1 { |
| 161 | if reg.Op == syntax.OpStar || reg.Op == syntax.OpQuest || reg.Op == syntax.OpRepeat { |
| 162 | return nil |
| 163 | } |
| 164 | return this.ParseKeywords(reg.Sub[0].String()) |
| 165 | } |
| 166 | |
| 167 | const maxComposedKeywords = 32 |
| 168 | |
| 169 | switch reg.Op { |
| 170 | case syntax.OpConcat: |
| 171 | var prevKeywords = []string{} |
| 172 | var isStarted bool |
| 173 | for _, sub := range reg.Sub { |
| 174 | if sub.String() == `\b` { |
| 175 | if isStarted { |
| 176 | break |
| 177 | } |
| 178 | continue |
| 179 | } |
| 180 | if sub.Op != syntax.OpLiteral && sub.Op != syntax.OpCapture && sub.Op != syntax.OpAlternate { |
| 181 | if isStarted { |
| 182 | break |
| 183 | } |
| 184 | continue |
| 185 | } |
| 186 | var subKeywords = this.ParseKeywords(sub.String()) |
| 187 | if len(subKeywords) > 0 { |
| 188 | if !isStarted { |
| 189 | prevKeywords = subKeywords |
| 190 | isStarted = true |
| 191 | } else { |
| 192 | for _, prevKeyword := range prevKeywords { |
| 193 | for _, subKeyword := range subKeywords { |
| 194 | keywords = append(keywords, prevKeyword+subKeyword) |
| 195 | |
| 196 | // 限制不能超出最大关键词 |
| 197 | if len(keywords) > maxComposedKeywords { |
| 198 | return nil |
| 199 | } |
| 200 | } |