How can I get token and login values from string via regex?

I have a string:

"Token token="ZuS6HNdwXsCDo2Moq2nx", login="login.login""

I want to get ZuS6HNdwXsCDo2Moq2nx and login.login.

How can I get token and login values using regexp?

I use /"\w+"/ to get token value, but I can't get login value. Maybe the is another alternative to this?


ts = 'Token token="ZuS6HNdwXsCDo2Moq2nx", login="login.login"'
#⇒ {
# "login" => "login.login",
# "token" => "ZuS6HNdwXsCDo2Moq2nx"

str='Token token="ZuS6HNdwXsCDo2Moq2nx", login="login.login"'

r = /
(?<=\stoken=) # match string in positive look behind
\"[a-z0-9]+\" # match > 0 letters or numbers between double quotes
/ix # case insensitive and extended mode
#=> "\"ZuS6HNdwXsCDo2Moq2nx\""

#=> "\"login.login\""

Because login contains (or can contain?) other characters than what is included in \w, you can use a custom character class: [\w.]+

Please note that the dot inside a character class matches itself, not any character.

You could try


but this would return token="ZuS6HNdwXsCDo2Moq2nx", but you can easily take the token out by .split('"')[1] for example.

This way makes sure the value you have returned is preceded by token= and surrounded by double quotes.

Category:ruby Time:2019-01-11 Views:0
Tags: ruby regex string

Related post

Copyright (C), All Rights Reserved.

processed in 0.592 (s). 13 q(s)