简体   繁体   English

正则表达式匹配没有开始和结束空格的字符串中的单词

[英]Regex match the words from a string without the start and end space

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从结果数组中删除所有空格:

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

But would like to do it only through regular expression and have no idea how to do it. 但是只想通过正则表达式来做,并且不知道该怎么做。

\w[\w ]*?(?:(?=\s*,)|$)

Explanation: 说明:

\w[\w ]*?

Matches word characters with 0 or more spaces in between, but never at the start. 匹配中间有0个或更多空格的单词字符,但从不在开头。 (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 comma 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 0到N个白色字符(空格字符:空格,制表符,换行符,回车符,垂直制表符)后跟
  • 1 or more word character(s). 1个或多个单词字符。

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

这可能是您正在寻找的捕获组,因此迭代\\ 1

\s*([\w\s]+)\s*

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

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