英文:
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
和" "
。
因此,你的正则表达式可以简化为:
"(?:[(=@\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" "
separately.
So, your regex can be simplified to:
"(?:[(=@\s]+|^)(MYNAME)"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论