Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

javascript - Regex for hyphenated words

I have hyphen separated words in paragraphs that I'm trying to extract.

I've tried following regex w+-w, however this is not working as expected.

Here's the complete code written in JavaScript.

var string = "time to eval-u-ate";
var result = string.match(/w+-w/g); // ["eval-u"]

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use following regex

((?:w+-)+w+)
  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

Demo

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>');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...