Reputation: 4819
I have a string something like:
test:awesome my search term with spaces
And I'd like to extract the string immediately after test:
into one variable and everything else into another, so I'd end up with awesome
in one variable and my search term with spaces
in another.
Logically, what I'd so is move everything matching test:*
into another variable, and then remove everything before the first :
, leaving me with what I wanted.
At the moment I'm using /test:(.*)([\s]+)/
to match the first part, but I can't seem to get the second part correctly.
Upvotes: 1
Views: 10220
Reputation: 10857
I am guessing you want to remove all the leading spaces before the second match too, hence I have \s+ in the expression. Otherwise, remove the \s+ from the expression, and you'll have what you want:
m = /^test:(\w+)\s+(.*)/.match("test:awesome my search term with spaces")
a = m[1]
b = m[2]
Upvotes: 0
Reputation: 30328
The first capture in your regular expression is greedy, and matches spaces because you used .
. Instead try:
matches = string.match(/test:(\S*) (.*)/)
# index 0 is the whole pattern that was matched
first = matches[1] # this is the first () group
second = matches[2] # and the second () group
Upvotes: 5
Reputation: 239270
Use the following:
/^test:(.*?) (.*)$/
That is, match "test:"
, then a series of characters (non-greedily), up to a single space, and another series of characters to the end of the line.
Upvotes: 4