user6275087
user6275087

Reputation: 33

vba regex - Get non space characters before space

So far I have this..

search_str = "-X made"
regEx.Pattern = "(\S*)[^\s*]"
regEx.IgnoreCase = True
regEx.Global = True
If regEx.test(search_str) Then
    Set matches = regEx.Execute(search_str) 
    extractStr = matches(0).SubMatches(0)
end if

I want extractStr to have -X ( anything before the first space), but I am not getting it.

Upvotes: 3

Views: 1322

Answers (1)

Paul S.
Paul S.

Reputation: 66364

There are a few issues with the pattern string "(\S*)[^\s*]"

  1. Non-escaped backslashes in the String literal In this particular language, backslash escapes aren't necessary (thanks Leviathan[1])
  2. \S and [^\s] are the same thing
  3. [foo*] means match f, o or *

You probably want something like this

regEx.Pattern = "(\S+)(?=\s)"

Which means

  • (\S+) match one or more non-whitespace (and remember the match) greedily until..
  • (?=\s) the next character is whitespace

Please note that a string like " " will not match, if you want this to match too, use the zero-or-more * in place of the one-or-more +


If you want to always match and you want to **always start from the beginning of the String, the RegExp becomes something like this

regEx.Pattern = "^(\S*)(?=\s|$)"

Where

  • ^ matches the beginning of the string
  • foo|$ matches foo or the end of the string

Upvotes: 4

Related Questions