使用正则表达式从字符串返回第一个外部结果 [英] Return first outer result from a string, using regular expressions

查看:19
本文介绍了使用正则表达式从字符串返回第一个外部结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串:

"{My {formatted {hi|hello}|formate{hi|hello} }  {option 1|option 2|option 3}}";

我想在{"和}"括号之间找到结果.

I want find the result in-between the "{" and "}" brackets.

结果也应该来自外层,不是{hi|hello}而是:

Also result should be from the outer layer, not {hi|hello} but:

"My {formatted {hi|hello}|formate{hi|hello} }  {option 1|option 2|option 3}"

推荐答案

/^{(.*)}$/ 将删除第一个和最后一个 { 和 <代码>}

/^{(.*)}$/ would remove the first and last { and }

通过 $var = preg_replace('/^{(.*)}$/', '$1', $your_text);

这也可以通过基本的字符串操作来实现,您可以将该正则表达式推进到 /^[^{]*{(.*)}[^{]*$/ 这将让您将字符放在所需字符串的前面和后面.同样,这可以通过字符串操作本身来完成,使用 substrstrrpos.

That particularly can be made with basic string operations too, you could advance that regex to /^[^{]*{(.*)}[^{]*$/ which would let you put chars in front of the desired string and after it. Again, this can be done with string operations itself, using substr and strrpos.

这篇关于使用正则表达式从字符串返回第一个外部结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆