Abibullah Rahamathulah
Abibullah Rahamathulah

Reputation: 2891

How do I extract these from a text

I want extract the assigned values in string.

"a=b  xxxxxx c = d xxxxxxxxx  e= f    g =h"

Like this IN RUBY using REGEX

["a=b","c=d","e=f", "g=h"]

I have tried:

'a= b sadfsf c= d'.scan(/\w=(\w+)/) 

Upvotes: 0

Views: 103

Answers (3)

Arup Rakshit
Arup Rakshit

Reputation: 118261

s = "a=b  xxxxxx c = d xxxxxxxxx  e= f    g =h"
s.scan(/[[:alpha:]][[:blank:]]*=[[:blank:]]*[[:alpha:]]/).map{|e| e.delete(" ")}
# => ["a=b", "c=d", "e=f", "g=h"]

Upvotes: 0

Tall Paul
Tall Paul

Reputation: 2450

It splits the string with the regex and then it stores it in an array

It then removes the white space around the = sign

str = "a=b  xxxxxx c = d xxxxxxxxx  e= f    g =h"
results = str.scan(/[\w]+\s*\=\s*[\w]+/)
results.each { |x| x.gsub!(/\s+/, "")}

Upvotes: 1

sawa
sawa

Reputation: 168071

"a=b  xxxxxx c = d xxxxxxxxx  e= f    g =h"
.scan(/(\w+)\s*=\s*(\w+)/).map{|kv| kv.join("=")}

# => ["a=b", "c=d", "e=f", "g=h"]

Upvotes: 4

Related Questions