检索特定模式内的值
我有一个像这样的模式,
"The world is #bright# and #beautiful#"
我需要检索 # # 内的字符串“bright”,“beautiful”。任何指针
我的解决方案(感谢Bolu):
string s = "The world is #bright# and #beautiful#";
string[] str = s.Split('#');
for (int i = 0; i <= str.Length - 1; i++)
{
if (i % 2 != 0)
{
Response.Write(str[i] + "<br />");
}
}
i have a pattern as like this
"The world is #bright# and #beautiful#"
i need to retrieve the string "bright","beautiful" inside # # .. any pointers
My solution (thanks to Bolu):
string s = "The world is #bright# and #beautiful#";
string[] str = s.Split('#');
for (int i = 0; i <= str.Length - 1; i++)
{
if (i % 2 != 0)
{
Response.Write(str[i] + "<br />");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果你想要的只是 ## 中的字符串,那么不需要正则表达式,只需使用 string.Split:
之后,你所需要的就是从 中获取偶数项(索引:1,3,5....)
字符串[]项
If all you want is the string inside ##, then no need for regex, just use string.Split:
After that, all you need is to get the even item (with index: 1,3,5....) from the
string[] tem
只要不能嵌套
#...#
序列,#([^#]+)#
就可以工作,并且会捕获 #' 之间的内容作为第一个反向引用。解释:
As long as you can't have nested
#...#
sequences,#([^#]+)#
will work, and will capture the content between #'s as the first backreference.Explanation:
查看
Match
对象:当然,当字符串中包含两个以上 # 时,这种情况就会失败。那么你可能想要进行非贪婪匹配。这可以使用正则表达式“
#(.*?)#
”来完成。这将匹配两个升号之间的最短字符串,并且仍然具有第一组中的内容。Check out the
Match
object:Of course this breaks down when you have more than two #'s in your string. Then you probably want to do a non-greedy match. This can be done with the regex "
#(.*?)#
". This will match the shortest string between two sharps and still have the contents in the first group.您需要设置一个
Capturing Group
,方法是将要捕获的部分括在圆括号()
中,并可选择指定捕获的名称:可以通过使用此代码:
或使用命名参数:
可以使用此代码访问:
You need to set up a
Capturing Group
by wrapping the part you want to capture in round brackets()
and optionally specifying a name for the capture:which can be accessed by using this code:
Or with a named parameter:
which can be accessed by using this code: