Home > Mobile >  Match every word, including non-a-z digits
Match every word, including non-a-z digits

Time:03-02

I'm really struggling to get a regex working. All I want to do is something that would capture a string and its trailing space and put that as an entry into an array.

For example:

"RegExr #was created by gskinner.com, and is proudly hosted by Media Temple.

Edit the Expression & Text to see matches."

["RegExr ", "#was ", "created ",  "by ", gskinner.com " ... "& " ... "matches. "  etc...]

I'm trying to do the following in a React App:

console.log("matches are: ", message.match(/(\w \s|#\w \s|\s )/));
return message.match(/((\w  ?))/);
// return message.split(" ");

I found that the split function was created some weird issues for me so I wanted just to have the matches function return an array of the results I specified above.

When I log out some attempts I just get weird results no matter what I try, like this:

e.g.

matches are:  (2) ["Hey ", "Hey ", index: 0, input: "Hey Martin Im not sure how to make the font in this box bigger #ZX81", groups: undefined]

Can someone help it is really blocking some progress on my app.

CodePudding user response:

To get all non-whitespace char chunks with any adjoining whitespace, you can use

message.match(/\s*\S \s*/g)

See the regex demo. The g flag will make it extract all matches of

  • \s* - zero or more whitespace chars
  • \S - one or more non-whitespace chars
  • \s* - zero or more whitespace chars.

See a JavaScript demo:

const message = "RegExr #was created by gskinner.com, and is proudly hosted by Media Temple. Edit the Expression & Text to see matches.";
console.log(message.match(/\s*\S \s*/g));

  • Related