Jorge
Jorge

Reputation: 13

How to use Regex to find a string with only spaces delimiting it?


I'm trying to parse a string that is only whitespace delimited.

I am currently using /\b[somestring]\b/

But i don't want it to pick up words that have any punctuation next to it.

So if i parsed this string:

"Trying to,\n
test this out,\n
but Trying to do this has taken a while.\n
Trying to do stuff is fun,\n
but i am stuck"

with /\bTrying To\b/

I find three, but i only want two because i don't want to include

"Trying to,"

--Edit

Expected output

Trying To
Trying To

Upvotes: 1

Views: 57

Answers (2)

Federico Piazza
Federico Piazza

Reputation: 31035

If I understood correctly your question, then you can use a regex lookahead like this:

Trying to(?=\s)

Working demo

The idea is to search for your string Trying to that is following with a space character

Edit: if you want to include those having \n, then you can use:

Trying to(?=\s|\\n)

Btw, if you want to include the literal space and the literal \n, then you don't need to use a regex lookahead, but simple group like this:

Trying to(?:\s|\\n)

Upvotes: 2

Greenbeard
Greenbeard

Reputation: 508

Maybe I am misunderstanding what you want, but should this work? /(?:^| )Trying to /gm, if you don't want all matches you could get rid of the g flag but please note this answer requires the m flag if you want new lines to work. Or if for some reason you don't want to deal with regex flags the following should work: /(?:^|\n| )Trying to /.

Upvotes: 0

Related Questions