How to find if input has 0s at the beginning in Ruby - ruby

I want to detect if input has 0 at the beginning and erase them. I came up the following code. But this detect 0 anywhere in input. How can I change this to detect 0s at the beginning?
if input.include?("0")
#input = input.gsub(/^0+/,"")
end

I think it is simplier to:
...my_string.start_with? "0"...
if it is not a string, simply cast it before (to_s). But there are other methods like:
...my_string.match(/\A0/)...
Or:
...if (my_string[0] == "0") ....
In cases that your string is multiline, all these method wil match the first character of the String. If you want to match any 0 on start of any line
...my_string.match(/^0/)...

Related

How do I regex-match an unknown number of repeating elements?

I'm trying to write a Ruby script that replaces all rem values in a CSS file with their px equivalents. This would be an example CSS file:
body{font-size:1.6rem;margin:4rem 7rem;}
The MatchData I'd like to get would be:
# Match 1 Match 2
# 1. font-size 1. margin
# 2. 1.6 2. 4
# 3. 7
However I'm entirely clueless as to how to get multiple and different MatchData results. The RegEx that got me closest is this (you can also take a look at it at Rubular):
/([^}{;]+):\s*([0-9.]+?)rem(?=\s*;|\s*})/i
This will match single instances of value declarations (so it will properly return the desired Match 1 result), but entirely disregards multiples.
I also tried something along the lines of ([0-9.]+?rem\s*)+, but that didn't return the desired result either, and doesn't feel like I'm on the right track, as it won't return multiple result data sets.
EDIT After the suggestions in the answers, I ended up solving the problem like this:
# search for any declarations that contain rem unit values and modify blockwise
#output.gsub!(/([^ }{;]+):\s*([^}{;]*[0-9.]rem+[^;]*)(?=\s*;|\s*})/i) do |match|
# search for any single rem value
string = match.gsub(/([0-9.]+)rem/i) do |value|
# convert the rem value to px by multiplying by 10 (this is not universal!)
value = sprintf('%g', Regexp.last_match[1].to_f * 10).to_s + 'px'
end
string += ';' + match # append the original match result to the replacement
match = string # overwrite the matched result
end
You can't capture a dynamic number of match groups (at least not in ruby).
Instead you could do either one of the following:
Capture the whole value and split on space
Use multilevel matching to capture first the whole key/value pair and secondly match the value. You can use blocks on the match method in ruby.
This regex will do the job for your example :
([^}{;]+):(?:([0-9\.]+?)rem\s?)?(?:([0-9\.]+?)rem\s?)
But whith this you can't match something like : margin:4rem 7rem 9rem
This is what I've been able to do: DEMO
Regex: (?<={|;)([^:}]+)(?::)([^A-Za-z]+)
And this is what my result looks like:
# Match 1 Match 2
# 1. font-size 1. margin
# 2. 1.6 2. 4
As #koffeinfrei says, dynamic capture isn't possible in Ruby. Would be smarter to capture the whole string and remove spaces.
str = 'body{font-size:1.6rem;margin:4rem 7rem;}'
str.scan(/(?<=[{; ]).+?(?=[;}])/)
.map { |e| e.match /(?<prop>.+):(?<value>.+)/ }
#⇒ [
# [0] #<MatchData "font-size:1.6rem" prop:"font-size" value:"1.6rem">,
# [1] #<MatchData "margin:4rem 7rem" prop:"margin" value:"4rem 7rem">
# ]
The latter match might be easily adapted to return whatever you want, value.split(/\s+/) will return all the values, \d+ instead of .+ will match digits only etc.

how to check whether the string taken through gui is a binary string in matlab?

I am working on a watermarking project that embeds binary values (i.e 1s and 0s) in the image, for which I have to take the input from the user, and check certain conditions such as
1) no empty string
2) no other character or special character
3) no number other than 0 and 1
is entered.
The following code just checks the first condition. Is there any default function in Matlab to check whether entered string is binary
int_state = get(handles.edit1,'String'); %edit1 is the Tag of edit box
if isempty(int_state)`
fprintf('Error: Enter Text first\n');
else
%computation code
end
There is no such standard function, but the check can be easily implemented.
Use this error condition:
isempty(int_state) || any(~ismember(int_state, '01'))
It returns false (no error) if the string is non-empty and composed of '0's and '1's only.
The function ismember returns a boolean array that indicates for every character in int_state whether it is contained in the second argument, '01'. The advantage is that this can be generalized to arbitrary sets of allowed characters.
I think the 2nd and 3rd can be combined together as 1 condition: your input string can only be a combination of 0 and 1? If it is so, then a small trick with findstr can do that:
if length(findstr(input_str, '1')) + length(findstr(input_str, '0')) == length(input_str)
condition_satisfied;
end
tf = isnumeric(A) returns true if A is a numeric array and false otherwise.
A numeric array is any of the numeric types and any subclasses of those types.
isnumeric(A)
ans =
1 (when A is numeric).

What does the /^ symbol mean in Ruby?

A friend of mine is trying to explain to me the answer to this problem:
Define a method binary_multiple_of_4?(s) that takes a string and returns true if the string represents a binary number that is a multiple of 4.
However, his example he gave is this:
if (s) == "0"
return true
end
if /^[01]*(00)$/.match(s) #|| /^0$/.match(s)
return true
else
return false
end
It works, because the software we use says there were no errors, but I don't understand why, or what /^ means, and how it's used.
If you could also explain the /^0$/.match(s), that would be great too.
Thanks!
what he is doing is using regular expressions, see: http://www.tutorialspoint.com/ruby/ruby_regular_expressions.htm
To break it down, there is a pattern that is matched inside the slashes /pattern/ and every character means something. ^ means start of the line [01] means match a 0 or a 1, * means match the previous thing ([01]) zero or more times, and (00) means match 00, and $ means match the end of the line.
If you want to know what /^0$/ matches, you should definitely try to figure it out based on the information in my post or the link I provided. Here's the answer though (hover to view):
It matches the beginning of the line, zero, the end of a line.

Regex for series of four digits each up to 100

I'm trying to write a regex to validate a string and accepts only a series of four comma-separated digits, each up to 100. Something like this would be valid:
20,30,40,50
and these invalid:
120,0,20,0
20,30,40,ss
invalid_string
Any thoughts?
They're used for CMYK colours. We just need to store them here, not use them.
Number Range and Subroutine
In Ruby 2+, for a compact regex, use this:
^([0-9]|[1-9][0-9]|100)(?:,\g<1>){3}$
Explanation
The ^ anchor asserts that we are at the beginning of the string
The parentheses around ([0-9]|[1-9][0-9]|100) match a number from 0 to 100 and define subroutine #1
(?:,\g<1>) matches one comma and the expression defined by subroutine # 1
The {3} quantifier repeats that three times
The $ anchor asserts that we are at the end of the string
I'd save myself the headache of using regex for a number related problem. Also the validation message will look akward so it's better to make your own:
validate :that_string_has_only_4_numbers_upto_100
def that_string_has_only_4_numbers_upto_100
errors.add(:str, 'is not valid.') unless str.split(/,/).all? { |n| 1..100 === n.to_i }
end
Unless you a re regex jedi guru like #zx81 :p.
^(?:\d{1,2},){3}\d{1,2}$
Try this

how to remove all [d+] except the last [d+]?

i have a string like
/root/children[2]/header[1]/something/some[4]/table/tr[1]/links/a/b
and
/root/children[2]/header[1]/something/some[4]/table/tr[2]
how can i reproduce the string so that all the /\[\d+\]/ are removed except for the last /\[\d+\]/ ?
so i should end up with .
/root/children/header/something/some/table/tr[1]/links/a/b
and
/root/children/header/something/some/table/tr[2]
No loops for you. Use a lookahead assertion (?= ... ):
s.gsub(/\[\d+\](?=.*\[)/, "")
There's a reasonable explanation of the very useful lookaround operators here
We will have to use while loop, I guess. And here comes good ol' C-style-loop solution:
while s.gsub!(/(\[\d+\])(.*?)(\[\d+\])/, '\2\3'); end
It's a bit hard to read, so I'll explain. The idea is that we match the string with a pattern that requires two [\d+] blocks to persist in a string. In the replacement, we just delete the first one. We repeat it until string doesn't match (so it contains only one such block) and utilize the fact that gsub! doesn't perform substitution when string is unmatched.
I'm absolutely certain there's a more elegant solution, but this ought to get you going:
string = "/root/children[2]/header[1]/something/some[4]/table/tr[1]/links/a/b"
count = string.scan(/\[\d+\]/).size
index = 0
string.gsub(/\[\d+\]/) do |capture|
index += 1
index == count ? capture : ""
end
Try this:
str.scan(/\[\d+\]/)[0..-2].each {|match| str.sub!(match, '')}

Resources