正则表达式仅在行除破折号外没有字符时才匹配

Regex only match if line has no characters besides dash

本文关键字:字符 破折号 正则表达式      更新时间:2023-09-26

我正在尝试匹配和替换带有-(破折号)的行,其后面只有空格或换行符,如" _ -_ _ _ _ "或" - _ _ _ "或" _ _ _ _ - _ ",但不是" _ _ _ _ - _ asdf "或" - _ _ _ whatever"。如果字母在前面出现,它会匹配,如" _ asdf _ _ - _ _ _

我在文本区域内运行它,但我不断替换-的所有实例。

$('textarea[name="yaml"]').val(
    $('textarea[name="yaml"]').val().replace(/-'x20(?!.)/g,
      ""));           
}

我还尝试了-'x20(?!'w 'd)-'x20[^.],以及其他组合。

也许/-['W]*$/m?如果*至少需要一个空格,请将更改为+

"^.*- +$"

注意:这假设您真的只想要空格而不是空格"''s"

示例代码:

<!DOCTYPE html>
<html>
<body>
  <p>Click the button to replace "blue" with "red" in the paragraph below:</p>
  <p id="demo1">testing -</p>
  <p id="demo2">testing -</p>
  <p id="demo3">testing-</p>
  <p id="demo4">-</p>
  <p id="demo5">testing -</p>
  <p id="demo6">testing - tester</p>
  <p id="demo7">testing -tester</p>
  <button onclick="myFunction()">Try it</button>
  <script>
    function myFunction() {
      for (var i = 1; i <= 7; ++i) {
        var ele = "demo" + i;
        var str = document.getElementById(ele).innerHTML;
        var res = str.replace(/^.*- +$/gi, "!replaced!");
        document.getElementById(ele).innerHTML = res;
      }
    }
  </script>
</body>
</html>

如果我没看错,可以这样做。

 # /^(?=['S's])['sa-z]*['s-]*$/
 ^                      # BOS
 (?= ['S's] )           # Ensure string not empty
 ['sa-z]*               # Optional whitespaces or letters
 ['s-]*                 # Optional whitespace or dash, but nothing else
 $                      # EOS