简体   繁体   English

如何测试仅包含字母字符和破折号(-)的字符串[javascript]

[英]how to test a string that contains only letter characters and dash(-) [javascript]

I need to create a regex for a word that contains only letter characters and the dash symbol (-). 我需要为仅包含字母字符和破折号(-)的单词创建一个正则表达式。 It can not be repeated in succession (eg --). 不能连续重复(例如-)。 Here's my regex function: 这是我的正则表达式函数:

var regex = new RegExp(/(\w*\-{0,1})*/);

This function should work for a word like: home-do g or even something like, home-dog-bird but not for something like home--dog . 此功能应适用于以下单词: home-do g甚至类似于home-dog-bird类的单词,但不适用于诸如home--dog类的单词。 How can I test this? 我该如何测试?

You can do that using negative look ahead. 您可以使用否定的前瞻来实现。

var regex=new RegExp(/^(\w|-(?!-))+$/);

What this does is matching something that contains only alphanumeric characters and - only if it's not followed by another - . 这样做是匹配仅包含字母数字字符的内容,并且-仅当其后没有另一个-时才匹配。

See https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions for more details on what's possible with the javascript regular expressions. 有关javascript正则表达式的更多信息,请参见https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

If you think about it the other way around (going backwards rather than forwards), you could make a regex that asserts that each match begins with one or more word characters and is followed by zero or more single dash, word pairs 如果您以相反的方式考虑它(向后而不是向前),则可以制作一个正则表达式来断言每个匹配都以一个或多个单词字符开头,然后是零个或多个单破折号,单词对

https://regex101.com/r/xT7aT5/2 https://regex101.com/r/xT7aT5/2

/^\w+(-\w+)*$/

Not sure if this is the best approach though. 不确定这是否是最好的方法。 I like Py.'s answer best atm. 我喜欢Py。的最佳自动取款机。

另一个没有提前通知的人:

/^(-?\w+)*-?$/

Another solution which looks for word and optional for a single dash and words. 另一种解决方案是查找单词,并为单个破折号和单词提供可选选项。

 function match(s) { return !!s.match(/^\\w+(\\-\\w+)*$/g); } document.write(match('dog') + '<br>'); document.write(match('dog-cat') + '<br>'); document.write(match('dog-cat-fish') + '<br>'); document.write(match('dog-cat--fish') + '<br>'); 

您也可以尝试以下方法:

var regex = new RegExp(/^(\w*(\-\w)\w*)*$/);

This will match in a body of text. 这将在文本正文中匹配。

/\w+(-\w+)+/

https://regex101.com/r/hU0xH7/1 https://regex101.com/r/hU0xH7/1

试试这个正则表达式/^([^-]*-{0,1}[^-]*)$/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM