正则表达式问题
给定以下类型的字符串:
“#First Thing# #Another One##No Space# Main String #After Main# #EndString#”
我想提出一个正则表达式,可以返回 # 包围的所有文本符号作为匹配。让我悲伤的事情之一是 # 符号既是开始分隔符又是结束分隔符。我对正则表达式的所有尝试都只是返回了整个字符串。另一个问题是字符串的一部分可能没有被 # 符号包围,如上面的子字符串“Main String”所示。有人有什么想法吗?我已经尝试过一些消极的后向断言,但还没有能够让它发挥作用。 # 组之间可能有也可能没有空格,但如果有的话我想忽略它们(不与它们匹配)。另一种选择是只编写一个字符串解析器例程,这将相当容易,但如果可能的话,我更愿意使用正则表达式。
Given the following type of string:
"#First Thing# #Another One##No Space# Main String #After Main# #EndString#"
I would like to come up with a regular expression that can return all the text surrounded by the # symbols as matches. One of the things giving me grief is the fact that the # symbol is both the opening and closing delimiter. All of my attempts at a regex have just returned the entire string. The other issue is that it is possible for part of the string to not be surrounded by # symbols, as shown by the substring "Main String" above. Does anyone have any ideas? I have toyed around with Negative Look-behind assertion a bit, but haven't been able to get it to work. There may or may not be a space in between the groups of #'s but I want to ignore them (not match against them) if there are. The other option would be to just write a string parser routine, which would be fairly easy, but I would prefer to use a regex if possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许像上面这样的东西会符合你的要求。
这将匹配两个哈希值之间的空格。唔。
我认为这将消除令人讨厌的空间。
Perhaps something like the above will match what you want.
This will match the space in between two hashes. Hmm.
That will get rid of the nasty space, I think.
[编辑]
我认为这就是您所需要的:
输入
#First Thing# #Another One##No Space# Main String #After Main#
匹配:First Thing
Another One
No Space
Main String
After Main
第二个匹配是之间的空格
Thing#
和#Another
。[编辑] 忽略空格:
如果你想忽略尾随空格:
[Edit]
I think that this is what you need:
With input
#First Thing# #Another One##No Space# Main String #After Main#
matches:First Thing
Another One
No Space
Main String
After Main
The second match is the space between
Thing#
and#Another
.[EDIT] To ignore space:
If you want to ignore trailing spaces:
试试这个。不应捕获第一个和最后一个组,并且 .*?应该是懒惰
我认为这是你真正需要的:
但它不会捕获
#
周围的Main String
Try this. The first and last groups should not be captured and the .*? should be lazy
I think this is what you really need:
but it will not capture the
#
's aroundMain String