Let's say I had someone enter the text 'Name: Bob'
Is there any way I can extract the right side of the colon if I know what's on the left?
For example, if I knew that the left side of the colon was 'Name,' could I extract 'Bob' and how would I do that?
Just by knowing that the string contains a colon, you can separate the string into two parts with the parts containing the string on each side of the colon.
let str = "Name: Bob"
let comp = str.components(separatedBy: ":") //returns an array of strings
let name = comp[1] //returns "Bob"
If you also want to remove the whitespace before the name, you can either do let comp = str.components(separatedBy: ": ") or if you want to be more generic, let name = comp[1].replacingOccurrences(of: " ", with: "")
Related
I am newbie in ruby. In my ruby program, there is a part of code for parsing geocode. The code is like below:
string = "GPS:3;S23.164865;E113.428970;88"
info = string.tr("GPS:",'')
info_array = info.split(";")
puts "GPS: #{info_array[0]},#{info_array[1]},#{info_array[2]}"
The code should split the string into 3 piece: 3, S23.164865 and E113.428970;88 and the expected output is
GPS: 3,S23.164865,E113.428970
but the result is:
GPS: 3,23.164865,E113.428970
Yes, the 'S' letter disappered...
If I use
string = "GPS:3;N23.164865;E113.428970;88"
info = string.tr("GPS:",'')
info_array = info.split(";")
puts "GPS: #{info_array[0]},#{info_array[1]},#{info_array[2]}"
, it prints expected result
GPS: 3,N23.164865,E113.428970
I am very confused why this happens. Can you help?
It looks like you were expecting String#tr to behave like String#gsub.
Calling string.tr("GPS:", '') does not replace the complete string "GPS:" with the empty string. Instead, it replaces any character from within the string "GPS:" with an empty string. Commonly you will find .tr() called with an equal number of input and replacement characters, and in that case the input character is replaced by the output character in the corresponding position. But the way you have called it with only the empty string '' as its translation argument, will delete any of G, P, S, : from anywhere within the string.
>> "String with S and G and a: P".tr("GPS:", '')
=> "tring with and and a "
Instead, use .gsub('GPS:', '') to replace the complete match as a group.
string = "GPS:3;S23.164865;E113.428970;88"
info = string.gsub('GPS:', '')
info_array = info.split(";")
puts "GPS: #{info_array[0]},#{info_array[1]},#{info_array[2]}"
# prints
GPS: 3,S23.164865,E113.428970
Here we've called .gsub() with a string argument. It is probably more often called with a regexp search match argument though.
The quiz problem:
You are given the following short list of movies exported from an Excel comma-separated values (CSV) file. Each entry is a single string that contains the movie name in double quotes, zero or more spaces, and the movie rating in double quotes. For example, here is a list with three entries:
movies = [
%q{"Aladdin", "G"},
%q{"I, Robot", "PG-13"},
%q{"Star Wars","PG"}
]
Your job is to create a regular expression to help parse this list:
movies.each do |movie|
movie.match(regexp)
title,rating = $1,$2
end
# => for first entry, title should be Aladdin, rating should be G,
# => WITHOUT the double quotes
You may assume movie titles and ratings never contain double-quote marks. Within a single entry, a variable number of spaces (including 0) may appear between the comma after the title and the opening quote of the rating.
Which of the following regular expressions will accomplish this? Check all that apply.
regexp = /"([^"]+)",\s*"([^"]+)"/
regexp = /"(.*)",\s*"(.*)"/
regexp = /"(.*)", "(.*)"/
regexp = /(.*),\s*(.*)/
Would someone explain why the answer was (1) and (2)?
Would someone explain why the answer was (1) and (2)?
The resulting strings will be similar to "Aladdin", "G" let's take a look at the correct answer #1:
/"([^"]+)",\s*"([^"]+)"/
"([^"]+)" = at least one character that is not a " surrounded by "
, = a comma
\s* = a number of spaces (including 0)
"([^"]+)" = like first
Which is exactly the type of strings you will get. Let's take a look at the above string:
"Aladdin", "G"
#^1 ^2^3^4
Now let's take at the second correct answer:
/"(.*)",\s*"(.*)"/
"(.*)" = any number (including 0) of almost any character surrounded by ".
, = a comma
\s* = any number of spaces (including 0)
"(.*)" = see first point
Which is correct as well as the following irb session (using Ruby 1.9.3) shows:
'"Aladdin", "G"'.match(/"([^"]+)",\s*"([^"]+)"/) # number 1
# => #<MatchData "\"Aladdin\", \"G\"" 1:"Aladdin" 2:"G">
'"Aladdin", "G"'.match(/"(.*)",\s*"(.*)"/) # number 2
# => #<MatchData "\"Aladdin\", \"G\"" 1:"Aladdin" 2:"G">
Just for completeness I'll tell why the third and fourth are wrong as well:
/"(.*)", "(.*)"/
The above regex is:
"(.*)" = any number (including 0) of almost any character surrounded by "
, = a comma
= a single space
"(.*)" = see first point
Which is wrong because, for example, Aladdin takes more than one character (the first point) as the following irb session shows:
'"Aladdin", "G"'.match(/"(.*)", "(.*)"/) # number 3
# => nil
The fourth regex is:
/(.*),\s*(.*)/
which is:
(.*) = any number (including 0) of almost any character
, = a comma
\s* = any number (including 0) of spaces
(.*) = see first point
Which is wrong because the text explicitly says that the movie titles do not contain any number of " character and that are surrounded by double quotes. The above regex does not checks for the presence of " in movie titles as well as the needed surrounding double quotes, accepting strings like "," (which are not valid) as the following irb session shows:
'","'.match(/(.*),\s*(.*)/) # number 4
# => #<MatchData "\",\"" 1:"\"" 2:"\"">
I know I can split a string into multiple substrings by giving a delimiter. I know I can also choose a substring based on character position like this:
sAddressOverflow = Right(sAddressLine1,5)
What I would like to do though is split an input string like this:
"123 South Main Street Apt. 24B"
But I only want to end up with two substrings which are split based on the first space to the left of the 25th character. So my desired output using the above input would be:
Substring1 = "123 South Main Street"
Substring2 = "Apt. 24B"
Is this possible?
Regular expressions have the advantage that you can configure your pattern independently from the location where you use it and that they are highly adaptable, so I prefer to do string manipulation with regular expressions. Unfortunately the pattern of Ansgar Wiechers does not exactly match your requirement. Here is one that does:
myString = "1234 6789A 234567 9B12 4567 890"
Set re = new RegExp
re.Pattern = "^(.{1,25}) (.*)$"
Set matches = re.Execute(myString)
wscript.echo "leftpart: " & matches(0).submatches(0)
wscript.echo "rightpart: " & matches(0).submatches(1)
There is no such inbuilt function available,
but you might want to try this,
add = "123 South Main Street Apt. 24B"
valid = Left(add,25)
arr = Split(valid)
char= InStrRev(add,arr(UBound(arr)))-1
address1 = Left(add,char)
address2= Right(add,Len(add)-char)
Wscript.echo address1
Wscript.echo address2
this might not be the perfect way, but it works !!!
You can do this with a regular expression, but you need a well defined format:
addr = "123 South Main Street Apt. 24B"
Set re = New RegExp
re.Pattern = "^(\d+ .*) +(apt\. +\d+(.*?))$"
re.IgnoreCase = True
Set m = re.Execute(addr)
If m.Count > 0 Then
WScript.Echo m(0).SubMatches(0)
WScript.Echo m(0).SubMatches(1)
End If
By "well-defined format" I mean that you need some "anchors" (or fix points) in your expression to identify the parts in the string. In the example the anchor is the substring "apt." followed by one or more digits.
can i do something like this?
string = "123" + rand(10).to_s + "abc"
=> "1237abc"
string.include?("123" + string.any_character(1) + "abc") # any_character(digit)
=> true
the point is to know a part of a string like lets say a html tag string, testing for something like Name Changes Every Day
and easily find the title from the source every time no matter what it might be, but for me, it will always be one character, soooooo, any help here?
Try that code:
string = "123" + rand(10).to_s + "abc"
string =~ /123\dabc/
0 means that pattern starts at 0 character. This return nil when pattern doesnt match. If you want to match only whole text change /123\dabc/ into /^123\dabc$/
You can just use regular expressions with ruby. Example:
string = "123" + rand(10).to_s + "abc"
string.match /123\dabc/
I am trying to split a string at the character ":" but cant create two separate strings from the split. If somebody could help me, I would appreciate it.
In RealBasic, the Split method doesn't create two (or more) separate strings but rather a single string array.
Dim s() As String = Split("Zero:One:Two", ":")
's() now contains the substrings like so:
's(0) = "Zero"
's(1) = "One"
's(2) = "Two"
Actually, the code is incorrect. It should be:
Dim s() As String = Split("Zero:One:Two", ":")
If you don't pass in the delimiter it assumes a space which wouldn't work in this case.
The online docs are at http://docs.realsoftware.com/index.php/Split
Split is best for actually splitting the text, but you can also use the string-manipulation methods: Left, Right, Mid and InStr.