正则表达式匹配行的开头或一组字符

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

Regular expression matching beginning of line OR a set of characters

问题

起初我以为这应该很简单,我只是忽略了什么,但是到目前为止,凭借我有限的正则表达式知识,我无法解决这个问题。

我有一个正则表达式,类似于 [一些字符]MYNAME,实际的内容是:

	rx = rx + `[ ,\t,,\,,\(,=,@,\s]+(MYNAME)`

我希望这个正则表达式能够同时检测以MYNAME开头的行。所以问题是,有没有办法在[]内部添加^和其他字符?或者将^[一些字符]进行逻辑“或”操作?

我无法在JavaScript或Go中使其工作。如果与此相关的问题有差异,我对Go语言的特定解决方案感兴趣。

英文:

At first I thought this must be very easy, I am just overlooking something, but so far with my limited knowledge of regex I can't figure this out,

I have a regex like [some characters]MYNAME actual thing is:

	rx = rx + `[ ,\t,,\,,\(,=,@,\s]+(MYNAME)`

I want this regex to <b>also</b> detect a line that <b>starts</b> with MYNAME.
So the question is, is there a way to add ^ inside [] with other things? or to OR the ^ with a [some characters]?

I can't make it work either with javascript or golang. If there are differences related to this matter, I am interested in the golang specific solutions.

答案1

得分: 4

你可以使用替代符号。此外,你的字符类中有一些不必要的字符:

  • 我不知道那些逗号的作用是什么?你是打算将它们作为分隔符使用吗?如果是的话,请将它们删除。
  • 此外,在字符类中不需要转义 (
  • 由于你已经添加了 \s,所以不需要单独添加 \t&quot; &quot;

因此,你的正则表达式可以简化为:

"(?:[(=@\s]+|^)(MYNAME)"
英文:

You can use alternation. Also, there are some unnecessary characters in your character class:

  • I don't know what those commas are supposed to do? Did you intent them to act as separator? If yes, remove them.
  • Also, you don't need to escape ( in a character class.
  • Since you have added \s, you don't need to add \t and &quot; &quot; separately.

So, your regex can be simplified to:

&quot;(?:[(=@\s]+|^)(MYNAME)&quot;

huangapple
  • 本文由 发表于 2013年10月9日 02:16:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/19255274.html
匿名

发表评论

匿名网友

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

确定