正则表达式,用于连字 [英] Regex for hyphenated words
本文介绍了正则表达式,用于连字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要提取的段落中有连字符分隔的单词.
I have hyphen separated words in paragraphs that I'm trying to extract.
我已经尝试过使用正则表达式 \ w +-\ w
,但是这种方式无法正常工作.
I've tried following regex \w+-\w
, however this is not working as expected.
这是用JavaScript编写的完整代码.
Here's the complete code written in JavaScript.
var string = "time to eval-u-ate";
var result = string.match(/\w+-\w/g); // ["eval-u"]
这将返回字符串 eval-u
.我希望结果为 eval-u-ate
.如何修改正则表达式以匹配完整的带连字符的单词.
This returns the string eval-u
. I want the result to be eval-u-ate
. How can I modify the regex to match complete hyphenated words.
推荐答案
您可以使用以下正则表达式
You can use following regex
((?:\w+-)+\w+)
-
(?:\ w +-)+
:匹配一个或多个字母数字字符,包括下划线符号和连字符.(?:
将使其不添加到捕获的组中 -
\ w +
:匹配一个或多个字母数字字符,包括下划线符号 -
()
:捕获组.可以使用$ n
访问匹配项,其中n
是捕获组号.$ 1
,因为它是第一个捕获组. -
g
:使用全局标志获取所有可能的匹配项
(?:\w+-)+
: Matches one or more alphanumeric characters including underscore symbol followed by a hyphen.(?:
will make it not add in captured group\w+
: Matches one or more alphanumeric characters including underscore symbol()
: Capturing group. The matches can be accessed by using$n
wheren
is the capturing group number.$1
in this case as it is first capturing group.g
: Use global flag to get all possible matches
演示
var string = "time to eval-u-ate Lorem ipsum dolor sit amet, consectetur adipisicing elit. A sed, illum veritatis aut recusandae tempora possimus iure totam distinctio necessitatibus temporibus labore-numquam-dignissimos, officiis velit error-dolores nostrum ipsam.";
var matches = string.match(/((?:\w+-)+\w+)/g);
document.write('<pre>' + JSON.stringify(matches, 0, 4) + '</pre>');
这篇关于正则表达式,用于连字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文