英文:
Regex for substring with same start and order
问题
我有一个字符串"abcdefg"。我想匹配任何等于删除末尾字符的子字符串。所以除了匹配"abcdefg"之外,字符串"abc"、"a"和"abcd"都应该匹配。
使用a|ab|abc|abcd|abcde|abcdef|abcdefg
可以工作,但实质上只是一个字符串列表。
有没有更节省空间的方法来做这个?
另外,我不能使用前瞻/后顾,因为Go语言不支持。
英文:
I have a string "abcdefg". I'd like to match any substring that is equivalent to removing characters at the end. So in addition to matching "abcdefg", the strings "abc", "a", and "abcd" should all match.
Using a|ab|abc|abcd|abcde|abcdef|abcdefg
will work, but it is essentially just a list of strings.
Is there a more space efficient way to do this?
Additionally, I can't use lookaheads/lookbehinds as they are not supported in Go.
答案1
得分: 5
我会手动编写一个检查代码。正则表达式并不是这个问题的好工具。但是,如果你坚持的话...
a(b(c(d(e(f(g)?)?)?)?)?)?
我会翻译为:
我会手动编写一个检查代码。正则表达式并不是这个问题的好工具。但是,如果你坚持的话...
a(b(c(d(e(f(g)?)?)?)?)?)?
英文:
I'd code up a check by hand. Regexes aren't really a good tool for this. But you know, if you insist...
a(b(c(d(e(f(g)?)?)?)?)?)?
答案2
得分: 0
你想要使用strings.HasPrefix
来检查字符串是否是"abcdefg"
的前缀。你还需要确保字符串非空,因为空字符串始终是一个有效的前缀:
match := s != "" && strings.HasPrefix("abcdefg", s)
这种方法比使用正则表达式要快得多。
英文:
You effectively want to use strings.HasPrefix
to check if the string is a prefix of "abcdefg"
. You also need to ensure the string is non-empty, since the empty string is always a valid prefix:
match := s != "" && strings.HasPrefix("abcdefg", s)
This will be much faster than using a regular expression.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论