我有以下字符串。
x = %q{ On the server side, my EJB3 application uses Spring for configuring all sorts of things. So my EJBs all look up various ApplicationContexts and use them as a sort of...well, I was going to say poor man's JNDI, but the reality is that JNDI in the J2EE environment is really a poor man's Spring. :-)
On the GUI side, I use it instead of resource injection to get access to my EJBs. That lets me test the GUI component with simple pojos. So ejb is very good technology}
我正在替换字符串"ejb"
,不区分大小写。我这样做:
y = x.gsub(/(ejb)/i, '<em>EJB</em>')
# => " On the server side, my <em>EJB</em>3 application uses Spring for configuring all sorts of things. So my <em>EJB</em>s all look up various ApplicationContexts and use them as a sort of...well, I was going to say poor man's JNDI, but the reality is that JNDI in the J2EE environment is really a poor man's Spring. :-)\n\nOn the GUI side, I use it instead of resource injection to get access to my <em>EJB</em>s. That lets me test the GUI component with simple pojos. So <em>EJB</em> is very good technology"
我的小写匹配为"ejb"
,我将替换为:"<em>EJB</em>"
。如何在不更换箱子的情况下更换它?我想要"<em>ejb</em>"
。
答案 0 :(得分:3)
x.gsub(/(ejb)/i, '<em>\1</em>')
答案 1 :(得分:0)
你想:
gsub(/(ejb)/i, "<em>#{$1}</em>")
答案 2 :(得分:0)
'test EjB123'.gsub(/ejb/i, "<em>#{$1}</em>")
=> "test <em>EjB</em>123"
答案 3 :(得分:0)
您可能想尝试:
x.gsub!(/(ejb)/i) {|m| "<em>#{$~}<em>"}
Special global variables
设置了一组Pattern matching
:
$~ is equivalent to ::last_match;
$& contains the complete matched text;
$` contains string before match;
$' contains string after match;
$1, $2 and so on contain text matching first, second, etc capture group;
$+ contains last capture group.
欲了解更多信息: Ruby Regex