<p>Sorry if this is not the right subreddit for questions, but I didn't see anything in the sidebar mentioning so.</p>
<p>I have a function with a compiled set of regexs, and I'm running them all against a string and want to return a map which maps the name of the regex to the match it found. I absolutely know how to do this in python, but I'm repeating code in golang and it just looks nasty. I know there has to be a better way.</p>
<p>This is exactly what I'd do in Python... compile once, name them, iterate across them and create the dict, then return that dict:</p>
<pre><code>import re
RE_FOO = re.compile(r'foo: (\w+)')
RE_BAR = re.compile(r'bar: (\w+)')
RE_BAZ = re.compile(r'baz: (\w+)')
SET_RE = {
'foo': RE_FOO,
'bar': RE_BAR,
'baz': RE_BAZ,
}
def matches_from_regexs(s):
matches = {}
for name, r in SET_RE.items():
match = r.match(s)
matches[name] = match.group(1) if match else None
return matches
</code></pre>
<p>Is there a way just as succinct in golang to do something like this? Right now I'm manually going through each named regex, and doing <code>if len(fooMatch) > 0 { matches["foo"] = fooMatch[1]</code>. There's got to be a way to name these and iterate through them.</p>
<p>Thanks! Sorry again if this is the wrong place for golang questions.</p>
<hr/>**评论:**<br/><br/>weirdasianfaces: <pre><p>Can you post your sample Go code? Your Go code should pretty much match that exact structure. This is what I came up with (it does not add non-matches to the result, but that's simple): <a href="http://play.golang.org/p/DOUEEvGH78" rel="nofollow">http://play.golang.org/p/DOUEEvGH78</a></p></pre>d4rch0n: <pre><p>Awesome! Exactly what I was trying to do. Thank you so much for this.</p>
<p>What I was mostly having trouble with finding is how to map a string to a regex, but it looks like <code>map[string]*regexp.Regexp</code> is what I was struggling to figure out.</p>
<p>I didn't realize golang was pass-by-value like C (from what I can see in the FAQ), so I see why they're returning a <code>*regexp.Regexp</code>. I didn't expect to see pointer notation in a garbage collected language. I thought they'd all be references.</p></pre>froggert: <pre><p>Hmm. I'm mobile right now, so syntax might be off. But, you can access the key and value at the same time in a map using range. Also, <a href="https://golang.org/pkg/regexp/#Regexp.FindString" rel="nofollow">FindString</a> is useful. If you need to distinguish between no match and matching the empty string, you can find with index.</p>
<pre><code>for k, v := range myMap {
if m := v.Find(s); m != "" {
result[k] = m
}
}
</code></pre>
<p>Hope that helps!</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传