正则表达式,用于连字 [英] Regex for hyphenated words

查看:50
本文介绍了正则表达式,用于连字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要提取的段落中有连字符分隔的单词.

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+)

  1. (?:\ w +-)+ :匹配一个或多个字母数字字符,包括下划线符号和连字符.(?:将使其不添加到捕获的组中
  2. \ w + :匹配一个或多个字母数字字符,包括下划线符号
  3. ():捕获组.可以使用 $ n 访问匹配项,其中 n 是捕获组号. $ 1 ,因为它是第一个捕获组.
  4. g :使用全局标志获取所有可能的匹配项
  1. (?:\w+-)+: Matches one or more alphanumeric characters including underscore symbol followed by a hyphen. (?: will make it not add in captured group
  2. \w+: Matches one or more alphanumeric characters including underscore symbol
  3. (): Capturing group. The matches can be accessed by using $n where n is the capturing group number. $1 in this case as it is first capturing group.
  4. 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>');

Regex101演示

这篇关于正则表达式,用于连字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆