正则表达式用空格分隔的一个或多个单词

时间:2022-01-21 16:51:51

I am looking for a regex where i have one or more words (possibly should cover alpha numeric also) separated by spaces (one or more spaces)

我正在寻找一个正则表达式,其中我有一个或多个单词(可能应该覆盖字母数字)也用空格(一个或多个空格)分隔

  1. " Test This stuff "
  2. “测试这个东西”
  3. " Test this "
  4. “测试这个”
  5. " Test "
  6. “测试”

Above are some examples of it

以上是它的一些例子

I wrote a regex to see what is repeating for #1

我写了一个正则表达式,看看#1重复了什么

\s*[a-zA-Z]*\s*[a-zA-Z]*\s*[a-zA-Z]*\s*

so i wanted to do something like {3} for repeating section.

所以我想做一些像{3}这样的重复部分。

But it does not seem to work.. I cant believe it is this difficult.

但它似乎不起作用..我不能相信这是困难的。

(\s*[a-zA-Z]*){3}

2 个解决方案

#1


21  

If you do not care just how many words you have, this would work:

如果你不在乎你有多少单词,这将有效:

[\w\s]+

\w is any alphanumeric. Replace it with a-zA-Z if you need only letters.

\ w是任何字母数字。如果只需要字母,请用a-zA-Z替换它。

#2


3  

I think you need something like this,

我想你需要这样的东西,

^\s*[A-Za-z0-9]+(?:\s+[A-Za-z0-9]+)*\s*$

DEMO

DEMO

OR

要么

^(?:\s+[A-Za-z0-9]+)+\s+$

DEMO

DEMO

#1


21  

If you do not care just how many words you have, this would work:

如果你不在乎你有多少单词,这将有效:

[\w\s]+

\w is any alphanumeric. Replace it with a-zA-Z if you need only letters.

\ w是任何字母数字。如果只需要字母,请用a-zA-Z替换它。

#2


3  

I think you need something like this,

我想你需要这样的东西,

^\s*[A-Za-z0-9]+(?:\s+[A-Za-z0-9]+)*\s*$

DEMO

DEMO

OR

要么

^(?:\s+[A-Za-z0-9]+)+\s+$

DEMO

DEMO