正则表达式仅在行除破折号外没有字符时才匹配
Regex only match if line has no characters besides dash
我正在尝试匹配和替换带有-
(破折号)的行,其后面只有空格或换行符,如" _ -_ _ _ _
"或" - _ _ _
"或" _ _ _ _ - _
",但不是" _ _ _ _ - _ 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
相关文章:
- 在JavaScript中输出转义字符
- 不同浏览器中的空白字符正则表达式行为
- Regex匹配除“”之外的所有字符;.js”;
- 拆分文本以每隔n个字符添加一行新行,并注意空格
- 使用RegExp查找url中的字符
- 如何为jQuery屏蔽输入插件创建一个允许字母数字、空格和重音字符的掩码
- 使用正则表达式将输入格式设置为单字符逗号、单字符逗号等
- 从所有单词中替换,即使用破折号分隔,第一个字符用大写[更简单的方法]
- 在键盘输入期间,在每 n 个字符后放置破折号
- 正则表达式仅在行除破折号外没有字符时才匹配
- â -字符显示代替em破折号(-)
- 允许alpha字符、空格、破折号、撇号和长度<= 50
- Javascript正则表达式,在每3和4个字符后添加破折号
- 需要javascript regex允许数字,单个和特定的alpha数字字符和破折号
- 为什么这个正则表达式可以在有或没有转义的连字符/破折号的情况下工作?
- 如何在JS比较中忽略破折号或连字符
- 无法读取id与点和破折号字符在javascript
- 允许一些特殊字符,如Javascript中的破折号
- Angularjs在ngSrc中使用连字符或破折号转义json
- 如何在使用lodash _.words时不分隔破折号/连字符