最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex match the words from a string without the start and end space - Stack Overflow

programmeradmin3浏览0评论

I'm trying to match some words from a string but with no success.

Let's say, for example, i have this string:

"word , word , two words, word"

What i'm trying to do is match the words, but without the space from start or end. But it should accept the spaces from in between the words. The array resulted from the match should be:

["word","word","two words","word"]

Could someone help or give me some insight on how would i go about doing this?

Thank you

Edit: what I've tried and succeed is doing it in two parts:

match(/[^(,)]+/g)

and using map to remove all the spaces from the resulting array:

map(value => value.trim());

But would like to do it only through regular expression and have no idea how to do it.

I'm trying to match some words from a string but with no success.

Let's say, for example, i have this string:

"word , word , two words, word"

What i'm trying to do is match the words, but without the space from start or end. But it should accept the spaces from in between the words. The array resulted from the match should be:

["word","word","two words","word"]

Could someone help or give me some insight on how would i go about doing this?

Thank you

Edit: what I've tried and succeed is doing it in two parts:

match(/[^(,)]+/g)

and using map to remove all the spaces from the resulting array:

map(value => value.trim());

But would like to do it only through regular expression and have no idea how to do it.

Share Improve this question edited Dec 6, 2017 at 7:27 user3477993 asked Dec 6, 2017 at 7:13 user3477993user3477993 2133 silver badges9 bronze badges 3
  • 2 post your attempts – Avinash Raj Commented Dec 6, 2017 at 7:14
  • Try this "word , word , two words, word".match(/(\w+\s*\w+)/g) – Hassan Imam Commented Dec 6, 2017 at 7:17
  • @HassanImam This does not work with three words. – Sweeper Commented Dec 6, 2017 at 7:24
Add a ment  | 

4 Answers 4

Reset to default 5
\w[\w ]*?(?:(?=\s*,)|$)

Explanation:

\w[\w ]*?

Matches word characters with 0 or more spaces in between, but never at the start. (lazy)

(?:(?=\s*,)|$)

This non-capturing group looks ahead for spaces followed by ,, or the end of string.

Try it here.

You can just split on ma surrounded by optional spaces on either side:

var str = "word , , word , two words, word";

var arr = str.split(/(?:\s*,\s*)+/);

console.log(arr);

//=> ["word", "word", "two words", "word"]

You can apply the following regex:

(\w+\s*\w+)

that matches

  • 1 or more word character(s) followed by
  • 0 to N white characters (whitespace character: space, tab, newline, carriage return, vertical tab) followed by
  • 1 or more word character(s).

http://www.rexegg./regex-quickstart.html

This might be what you're looking for with capture groups, so iterate over \1

\s*([\w\s]+)\s*
发布评论

评论列表(0)

  1. 暂无评论