正则表达式在行首匹配字符串分组

Regex match string grouping at start of line

我有一个像这样的降价字符串:

var str = "
  # Title here
  Some body of text
  ## A subtitle
  ##There may be no space after the title hashtags
  Another body of text with a Twitter #hashtag in it";

现在我想匹配并替换所有标题主题标签以向它们添加另一个主题标签。但是我需要避免匹配文本行中的主题标签(twitter 主题标签)。我正在尝试实现以下字符串:

var str = "
  ## Title here
  Some body of text
  ### A subtitle
  ###There may be no space after the title hashtags
  Another body of text with a Twitter #hashtag in it";

到目前为止,我已经得到了这个正则表达式,它可以完成工作,但也与 twitter 主题标签相匹配:

str = str.replace(/(#+)/g, "#");

每行文字后有回车符returns。如何在不影响文本中的主题标签的情况下实现此替换。

如果加上/m,可以用^匹配行首(不加/m,只匹配整个字符串的开头)。
然后,您可以使用 \s*(感谢 stribizhev)保留每行开头的所有空格。

str = str.replace(/^\s*#+/gm, "$&#");

演示:

// Note that multiline strings are not actually legal in JavaScript
var str = [
'  # Title here',
'  Some body of text',
'  ## A subtitle',
'  ##There may be no space after the title hashtags',
'  Another body of text with a Twitter #hashtag in it'
].join('\n');
document.write(str.replace(/^\s*#+/gm, "$&#"));
/* For demo only */
body{white-space:pre-line;font-family:monospace}