在Stack Exchange上反补代码片段


9

您的目标是输入任意文本,例如:

This is some text

并输出该格式的文本,以作为Stack Exchange上帖子(SE风格的Markdown)和注释(迷你Markdown)的代码,例如:

`This is some text`
`This is some text`

但是,它变得更加棘手。考虑输入:

Perl has a variable called $`

输出必须是

`` Perl has a variable called $` ``
`Perl has a varaible called $\``

格式化的完整规则是:

  • 完整帖子(完整的SE Markdown)

    • 第1步:计算字符串中没有连续多少个反引号的最小数字。让我们称之为n。(例如,对于字符串potaton为1,对于this is a backtick: `n为2,对于` `` ``` ````` ``````n为4。)

    • 步骤2:将字符串包装在n反引号中。如果字符串以反引号开头或结尾,则还必须使用空格换行。(例如,potato成为`potato`this is a backtick: `成为`` this is a backtick: ` ``` `` ``` ````` ``````成为```` ` `` ``` ````` `````` ````

  • 评论(迷你Markdown)

    • 裹在`和逃避所有`的用\`。(例如,potato成为`potato`this is a backtick: `成为this is a backtick: \`` `` ``` ````` ``````成为\` \`\` \`\`\` \`\`\`\`\` \`\`\`\`\`\`

这是 ; 以字节数为单位的最短答案将获胜。


那空间呢?``不会得到代码格式...
Justin

@Quincunx Hmm ...无论如何,您应该如何格式化代码中的空格?
门把手

我不知道。这篇文章是我学习如何格式化反引号的地方。
贾斯汀

2
评论表格也不适用\; 要格式化a \,您需要做``\``。此外,任何以“ run”结尾的\问题都会遇到相同的问题:asdf\产生`asdf`
Justin

Answers:


4

APL(90)

(是的,APL字符集确实适合一个字节,这是IBM的代码页907。

{⎕ML←3⋄(,/m,m,⍨{⍵=m:'\`'⋄⍵}¨⍵),⊂(⌽g),⍵,g←(''↑⍨∨/t[1,⍴t]),m/⍨0⍳⍨z∊⍨⍳⌈/0,z←,⊃⍴¨⍵⊂⍨t←⍵=m←'`'}

这个函数接受一个字符串,并返回一个由两个字符串组成的数组,其中第一个字符串是注释表示,第二个字符串是完整的帖子表示。

测试:

      backtickify←{⎕ML←3⋄(,/m,m,⍨{⍵=m:'\`'⋄⍵}¨⍵),⊂(⌽g),⍵,g←(''↑⍨∨/t[1,⍴t]),m/⍨0⍳⍨z∊⍨⍳⌈/0,z←,⊃⍴¨⍵⊂⍨t←⍵=m←'`'}
      ↑backtickify 'potato'
`potato`
`potato`

      ↑backtickify 'this is a backtick: `'
`this is a backtick: \``   
`` this is a backtick: ` ``

      ↑backtickify '` `` ``` ````` ``````'
`\` \`\` \`\`\` \`\`\`\`\` \`\`\`\`\`\``
```` ` `` ``` ````` `````` ````  

      ⍝ testcase for not wrapping with spaces
      ↑backtickify 'no`spaces``at````the`edges'
`no\`spaces\`\`at\`\`\`\`the\`edges`
```no`spaces``at````the`edges``` 

注意:为便于阅读,我给函数起了一个名字,使用它并不是严格必须的(您可以将参数放在匿名函数旁边),因此我没有计算。


2

露比119

s=gets.chop
c=1
c+=1while s=~/([^`]|\A)#{?`*c}([^`]|\z)/
puts ?`+s.gsub('`','\\\\`')+'`
'+?`*c+(s=~/$`|`^/?" #{s} ":s)+?`*c

取消高尔夫:

def backtickify str, comment = false
  return "`#{str.gsub '`', '\\\\`'}`" if comment
  c = 1
  c += 1 while str =~ /([^`]|\A)#{?` * c}([^`]|\z)/
  str = ' ' + str + ' ' if str[0] == ?` || str[-1] == ?`
  return ?` * c + str + ?` * c
end
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.