【问题标题】:Targeting a whitespace before the linebreak with Regex使用正则表达式在换行符之前定位一个空格
【发布时间】:2022-01-28 02:12:48
【问题描述】:

我想在符号和行尾的空格之后去掉 cmets,所以我的代码如下所示

function solution(input, markers) {
   let regexp = new RegExp("["+ markers.join('') + "].*","gi")
   let removeWhiteSpace = input.replace(regexp,"")
   return removeWhiteSpace.replace(/\s+$/g,"")
};

我有如下字符串

console.log(solution("apples, plums % and bananas\npears\noranges !applesauce",["%", "!"]))

我在定位“李子”之后的空白而不影响其他空白时遇到了麻烦。我可以在这个正则表达式中改进什么来定位那个空格。

【问题讨论】:

  • 你想要的输出是什么?您是否尝试删除 markers 中的符号并在字符串末尾去除任何多余的空格?更新您的问题。
  • 对不起,我没有看到你的评论。我应该写出更好的问题形式我的问题是通过这个正则表达式解决的 - /\s[%!].*/gi

标签: javascript regex comments whitespace


【解决方案1】:

您的代码所做的是匹配 '%' 或 '!' 之后的所有内容然后替换字符串末尾的空格。 如果您尝试删除标记中的符号并去除字符串末尾的任何多余空格,那么您可以在一行代码中执行此操作:

let regex = /(?:[%!]+\s*|\s*$)/gm
input.replace(regex, "")

正则表达式:/(?:[%!]+\s*|\s*$)/gm

(?:          Non capture group
  [%!]+\s*   zero or more spaces that follow one or more symbols (from marker var) 
  |          OR
   \s*$       zero or more spaces at the end of the input string
)

【讨论】:

  • 我想要做的是去掉注释符号之后的单词,所以我认为我的代码对我有用,但让我困扰的是新行之前的单词后面留下的空格。为了进一步澄清,我试图在这里解决这个问题link
猜你喜欢
  • 1970-01-01
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-28
  • 1970-01-01
  • 2020-06-16
相关资源
最近更新 更多