【问题标题】:Regex match string grouping at start of line正则表达式匹配行首的字符串分组
【发布时间】:2015-08-06 18:52:07
【问题描述】:

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

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";

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

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, "$1#");

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

【问题讨论】:

  • 你的var str = ...是一个有效的JS语法吗?
  • @anubhava 肯定不是。

标签: javascript regex replace markdown


【解决方案1】:

如果添加/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}

【讨论】:

  • 我猜应该使用\s*,否则那些没有前导空格的行将不会被修改。并且不需要将整个模式封闭到一个捕获组中,使用$& 反向引用。
  • @stribizhev 是的,谢谢你,编辑了我的答案。
  • 谢谢!正是我需要的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-05
  • 2013-12-25
相关资源
最近更新 更多