Drake
Drake

Reputation: 2451

regular expression: match any word until first space

I have the following line:

hshd    household   8/29/2007   LB

I want to match anything that comes before the first space (whitespace). So, in this case, I want to get back

hshd

Upvotes: 215

Views: 484534

Answers (9)

(^\S+)

This did the trick for me. (/gm)

You could test it in this

Upvotes: 1

darshan
darshan

Reputation: 39

^([^\s]+) use this it correctly matches only the first word you can test this using this link https://regex101.com/

Upvotes: 1

MaEtUgR
MaEtUgR

Reputation: 383

Derived from the answer of @SilentGhost I would use:

^([\S]+)

Check out this interactive regexr.com page to see the result and explanation for the suggested solution.

Upvotes: 12

Behzad
Behzad

Reputation: 3580

I think, a word was created with more than one letters. My suggestion is:

[^\s\s$]{2,}

Upvotes: 2

dsolimano
dsolimano

Reputation: 8986

Perhaps you could try ([^ ]+) .*, which should give you everything to the first blank in your first group.

Upvotes: 15

Jeremy Clarkson
Jeremy Clarkson

Reputation: 165

I think, that will be good solution: /\S\w*/

Upvotes: 4

w35l3y
w35l3y

Reputation: 8773

for the entire line

^(\w+)\s+(\w+)\s+(\d+(?:\/\d+){2})\s+(\w+)$

Upvotes: 6

Jeremy Stein
Jeremy Stein

Reputation: 19661

This should do it:

^\S*

Upvotes: 77

SilentGhost
SilentGhost

Reputation: 319601

([^\s]+)

works

Upvotes: 463

Related Questions