我正在努力学习正则表达式,我在网上发现了一些挑战问题,但很早就被难过了......我对此并不是很擅长:(无论如何,这里的问题让我难过 -
Each line beginning and ending with two asterisks gets surrounded with <h2> and </h2>, instead of the asterisks and surrounding white space
我知道有一些行以行开头并以^和&amp;结尾所以我想也许我应该用那些来找到&#34; **&#34;然后使用gsub代替,但后来我记得那会放入两个地方而且那不是我想要的所以我感到难过。
请帮帮我!
答案 0 :(得分:0)
如果我理解你的问题,这就是你需要的:
result = subject.gsub(/\A(\*\*)(.*?)(\*\*)\Z/, '<h2>\2</h2>')
正则表达式说明:
^(\*\*)(.*?)(\*\*)$
Assert position at the beginning of the string «^»
Match the regular expression below and capture its match into backreference number 1 «(\*\*)»
Match the character “*” literally «\*»
Match the character “*” literally «\*»
Match the regular expression below and capture its match into backreference number 2 «(.*?)»
Match any single character that is not a line break character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the regular expression below and capture its match into backreference number 3 «(\*\*)»
Match the character “*” literally «\*»
Match the character “*” literally «\*»
Assert position at the end of the string (or before the line break at the end of the string, if any) «$»
答案 1 :(得分:0)
string =<<-END_OF_STRING
Foo Bar
**Foo BAR**
Bazz
**Bazz**
**Not** Complete
END_OF_STRING
puts string.gsub(/^\*\*(.+)\*\*$/) { |m| "<h2>#{$1}</h2>" }
# Foo Bar
# <h2>Foo BAR</h2>
# Bazz
# <h2>Bazz</h2>
# **Not** Complete
答案 2 :(得分:0)
一种方法:
def doit(str)
sub = str[/^\s*\*{2}\s*(.*?)\s*\*{2}\s*/,1]
sub ? '<h2>' + sub + '</h2>' : str
end
str = ' ** Now is the time for all ** '
doit(str) #=> "<h2>Now is the time for all</h2>"
str = ' ** Now is the time for all * '
doit(str) #=> " ** Now is the time for all * "