Using regex to grab only digits or the decimal separator - ruby-on-rails

I have the following piece of code to grab the amount and another amount.
#payer_contract_params['payer'] = JSON.parse(#payer_contract_params['payer'])
#payer_contract_params['amount'] = #payer_contract_params['amount'].to_s.tr('$', '').tr(',','')
#payer_contract_params['stoploss_amount'] = #payer_contract_params['stoploss_amount'].to_s.tr('$', '').tr(',','')
It works, but it will only work in locales which use '$' as the currency and ',' as a separator. How could I Use regex to grab grab only digits or the decimal separator?

Use gsub like this #payer_contract_params['amount'].to_s.gsub(/[^\d,]/, '')
This will replace all characters that are not digits or comma.

It's simple
/(^\d+$)|(^\.$)/
Breakdown
() - Indicates a capturing group
^ - Indicates the regex starts with the following expression
\d - Matches any digit
+ - Mathes 1 or more of the previous selector
$ - Indicates the regex ends with the previous expression
| - Or
\. - Matches a period. Note the slash to escape it.

You can calculate your regex's in Ruby here at http://rubular.com/

Related

How to create a regular expression to match specific substrings inside brackets?

In my Ruby on Rails app I need a regex that accepts the following values:
{DD}
{MM}
{YY}
{NN}
{NNN}
{NNNN}
{NNNNN}
{NNNNNN}
upper and lowercase letters
the special characters -, _, . and #
I am still new to regular expressions and I came up with this:
/\A[a-zA-Z._}{#-]*\z/
This works pretty well already, however it also matches strings that should not be allowed such as:
}FOO or {YYY}
Can anybody help?
You may use
/\A(?:\{(?:DD|MM|YY|N{2,6})\}|[A-Za-z_.#-])*\z/
See Rubular demo
\A - start of string anchor
(?:\{(?:DD|MM|YY|N{2,6})\}|[A-Za-z_.#-])* - a non-capturing group ((?:...) that only groups sequences of atoms and does not create submatches/subcaptures) zero or more occurrences of:
\{(?:DD|MM|YY|N{2,6})\} - a { then either DD, or MM, YY, 2 to 6N followed with }
| - or
[A-Za-z_.#-] - 1 char from the set (ASCII letter, _, ., # or -)
\z - end of string.

How to find 2 Assignment operator in regex

I am trying to find 2 symbols together "+*" , "-/", or such and also I want to identify if it's "3-", "4-" "*4" and such. I will be looking for it inside and array or strings like such ["2" , "+", "3","/" , "2"]
If I understand your question correctly, you are trying to match a symbol followed by a number or a number followed by a symbol
the regex would look something like this
/^[+-\/\*]\d$|^\d[+-\/\*]$/
Breakdown
^ - Start of line
[+-\/\*] - Any one of the symbols. Asterisk and forward slash must be escaped
\d - Matches any digit (0 through 9)
$ - End of line
| - Or
^\d[+-\/\*]$ - starts with a digit and ends with a symbol.
Please let me know if this is what you are looking for. Otherwise I can fix this.
In Ruby, let's pretend you have an array as follows
array = ["2" , "+", "3","/" , "2"]
You can find if any two consecutive elements match the above pattern as follows
array.each_cons(2).to_a.any? { |combo| combo.join.match(/^[+-\/\*]\d$|^\d[+-\/\*]$/) }
Breakdown
Use the each_cons(2) function to find every two consecutive characters in the array
use the any? method to find if any elements in the array satisfy a condition
Iterate over every element and find if any of the two joined together match the regex pattern
I don't get the second part about "3-" etc. But the basic idea for the rest is:
your_array.each do |element|
result element.match([/\+\/-]{2}/)
end
Note that the following characters have to be escaped with a backslash when used in ruby:
. | ( ) [ ] { } + \ ^ $ * ?.

What does this pattern ^[%w-.]+$ mean in Lua?

Just came across this pattern, which I really don't understand:
^[%w-.]+$
And could you give me some examples to match this expression?
Valid in Lua, where %w is (almost) the equivalent of \w in other languages
^[%w-.]+$ means match a string that is entirely composed of alphanumeric characters (letters and digits), dashes or dots.
Explanation
The ^ anchor asserts that we are at the beginning of the string
The character class [%w-.] matches one character that is a letter or digit (the meaning of %w), or a dash, or a period. This would be the equivalent of [\w-.] in JavaScript
The + quantifier matches such a character one or more times
The $ anchor asserts that we are at the end of the string
Reference
Lua Patterns
Actually it will match nothing. Because there is an error: w- this is a start of a text range and it is out of order. So it should be %w\- instead.
^[%w\-.]+$
Means:
^ assert position at start of the string
[%w\-.]+ match a single character present in the list below
+ Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
%w a single character in the list %w literally (case sensitive)
\- matches the character - literally
. the literal character .
$ assert position at end of the string
Edit
As the OP changed the question and the tags this answer no longer fits as a proper answer. It is POSIX based answer.
As #zx81 comment:
%w is \w in Lua which means any alphanumeric characters plus "_"

Premature end of char-class

I had the regular expression for email validating following rules
The local-part of the e-mail address may use any of these ASCII characters:
Uppercase and lowercase English letters (a-z, A-Z)
Digits 0 to 9
Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
Character . (dot, period, full stop) provided that it is not the first or last character, and provided also that it does not appear two or more times consecutively.
/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i
It is working in Javascript but in Ruby http://rubular.com/ it gives error "Premature end of char-class".
How can i resolve this?
Brackets are part of regex syntax. If you want to match a literal bracket (or any other special symbol, for that matter), escape with a backslash.
this should work :
/^(([^<>()\[\]\\.,;:\s#\"]+(\.[^<>()\[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i
You should escape opening square brackets as well as closings inside the symbol range:
# ⇓ ⇓
/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)…/
This should be:
/^(([^<>()\[\]\\.,;:\s#\"]+(\.[^<>()\[\]\\.,;:\s#\"]+)*)…/
Hope it helps.
irb(main):016:0> /[[e]/
SyntaxError: (irb):16: premature end of char-class: /[[e]/
from /ms/dist/ruby/PROJ/core/2.0.0-p195/bin/irb:12:in `<main>'
In JavaScript regular expression engine, you don't need to escape [ inside a character group []. However, you have to use \[ in Ruby regular expression.
/^(([^<>()\[\]\\.,;:\s#\"]+(\.[^<>()\[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i

string format checking (with partly random string)

I would like to use regular expression to check if my string have the format like following:
mc_834faisd88979asdfas8897asff8790ds_oa_ids
mc_834fappsd58979asdfas8897asdf879ds_oa_ids
mc_834faispd8fs9asaas4897asdsaf879ds_oa_ids
mc_834faisd8dfa979asdfaspo97asf879ds_dv_ids
mc_834faisd111979asdfas88mp7asf879ds_dv_ids
mc_834fais00979asdfas8897asf87ggg9ds_dv_ids
The format is like mc_<random string>_oa_ids or mc_<random string>_dv_ids . How can I check if my string is in either of these two formats? And please explain the regular expression. thank you.
That's a string start with mc_, while end with _oa_ids or dv_ids, and have some random string in the middle.
P.S. the random string consists of alpha-beta letters and numbers.
What I tried(I have no clue how to check the random string):
/^mc_834faisd88979asdfas8897asff8790ds$_os_ids/
Try this.
^mc_[0-9a-z]+_(dv|oa)_ids$
^ matches at the start of the line the regex pattern is applied to.
[0-9a-z] matces alphabetic and numeric chars.
+ means that there should be one or more chars in this set
(dv|oa) matches dv or oa
$ matches at the end of the string the regex pattern is applied to.
also matches before the very last line break if the string ends with a line break.
Give /\Amc_\w*_(oa|dv)_ids\z/ a try. \A is the beginning of the string, \z the end. \w* are one or more of letters, numbers and underscores and (oa|dv) is either oa or dv.
A nice and simple way to test Ruby Regexps is Rubular, might have a look at it.
This should work
/mc_834([a-z,0-9]*)_(oa|dv)_ids/g
Example: http://regexr.com?2v9q7

Resources