正则表达式用于匹配具有相同起始和顺序的子字符串。

huangapple go评论80阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2021年9月24日 06:23:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/69307514.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定