given a string as follow:
randomstring1-randomstring2-3df83eeff2
How can I use a ruby regex or some other ruby/rails friendly method to find everything up until the first dash -
In the example above that would be: randomstring1
Thanks
You can use this pattern: ^[^\-]*
mystring = "randomstring1-randomstring2-3df83eeff2"
firstPart = mystring[0, mystring.index("-")]
Otherwise, I think the best regex is #polishchuk's.
It matches from the beginning of the string, matches as many as possible of anything that is not a dash -.
Using irb you can do this too:
>> a= "randomstring1-randomstring2-3df83eeff2"
=> "randomstring1-randomstring2-3df83eeff2"
>> a.split('-').first
=> "randomstring1"
>>
For this situation, the index solution given by agent-j is probably better. If you did want to use regular expressions, the following non-greedy (specified by the ?) regex would grab it:
(^.*?)-
You can see it in Rubular.
Related
I am building a Rails 5.2 app.
In this app I got outputs from different suppliers (I am building a webshop).
The name of the shipping provider is in this format:
dhl_freight__233433
It could also be in this format:
postal__US-320202
How can I remove all that is before (and including) the __ so all that remains are the things after the ___ like for example 233433.
Perhaps some sort of RegEx.
A very simple approach would be to use String#split and then pick the second part that is the last part in this example:
"dhl_freight__233433".split('__').last
#=> "233433"
"postal__US-320202".split('__').last
#=> "US-320202"
You can use a very simple Regexp and a ask the resulting MatchData for the post_match part:
p "dhl_freight__233433".match(/__/).post_match
# another (magic) way to acces the post_match part:
p $'
Postscript: Learnt something from this question myself: you don't even have to use a RegExp for this to work. Just "asddfg__qwer".match("__").post_match does the trick (it does the conversion to regexp for you)
r = /[^_]+\z/
"dhl_freight__233433"[r] #=> "233433"
"postal__US-320202"[r] #=> "US-320202"
The regular expression matches one or more characters other than an underscore, followed by the end of the string (\z). The ^ at the beginning of the character class reads, "other than any of the characters that follow".
See String#[].
This assumes that the last underscore is preceded by an underscore. If the last underscore is not preceded by an underscore, in which case there should be no match, add a positive lookbehind:
r = /(?<=__[^_]+\z/
This requires the match to be preceded by two underscores.
There are many ruby ways to extract numbers from string. I hope you're trying to fetch numbers out of a string. Here are some of the ways to do so.
Ref- http://www.ruby-forum.com/topic/125709
line.delete("^0-9")
line.scan(/\d/).join('')
line.tr("^0-9", '')
In the above delete is the fastest to trim numbers out of strings.
All of above extracts numbers from string and joins them. If a string is like this "String-with-67829___numbers-09764" outut would be like this "6782909764"
In case if you want the numbers split like this ["67829", "09764"]
line.split(/[^\d]/).reject { |c| c.empty? }
Hope these answers help you! Happy coding :-)
I need a regex that will only find matches where the entire string matches my query.
For instance if I do a search for movies with the name "Red October" I only want to match on that exact title (case insensitive) but not match titles like "The Hunt For Red October". Not quite sure I know how to do this. Anyone know?
Thanks!
Try the following regular expression:
^Red October$
By default, regular expressions are case sensitive. The ^ marks the start of the matching text and $ the end.
Generally, and with default settings, ^ and $ anchors are a good way of ensuring that a regex matches an entire string.
A few caveats, though:
If you have alternation in your regex, be sure to enclose your regex in a non-capturing group before surrounding it with ^ and $:
^foo|bar$
is of course different from
^(?:foo|bar)$
Also, ^ and $ can take on a different meaning (start/end of line instead of start/end of string) if certain options are set. In text editors that support regular expressions, this is usually the default behaviour. In some languages, especially Ruby, this behaviour cannot even be switched off.
Therefore there is another set of anchors that are guaranteed to only match at the start/end of the entire string:
\A matches at the start of the string.
\Z matches at the end of the string or before a final line break.
\z matches at the very end of the string.
But not all languages support these anchors, most notably JavaScript.
I know that this may be a little late to answer this, but maybe it will come handy for someone else.
Simplest way:
var someString = "...";
var someRegex = "...";
var match = Regex.Match(someString , someRegex );
if(match.Success && match.Value.Length == someString.Length){
//pass
} else {
//fail
}
Use the ^ and $ modifiers to denote where the regex pattern sits relative to the start and end of the string:
Regex.Match("Red October", "^Red October$"); // pass
Regex.Match("The Hunt for Red October", "^Red October$"); // fail
You need to enclose your regex in ^ (start of string) and $ (end of string):
^Red October$
If the string may contain regex metasymbols (. { } ( ) $ etc), I propose to use
^\QYourString\E$
\Q starts quoting all the characters until \E.
Otherwise the regex can be unappropriate or even invalid.
If the language uses regex as string parameter (as I see in the example), double slash should be used:
^\\QYourString\\E$
Hope this tip helps somebody.
Sorry, but that's a little unclear.
From what i read, you want to do simple string compare. You don't need regex for that.
string myTest = "Red October";
bool isMatch = (myTest.ToLower() == "Red October".ToLower());
Console.WriteLine(isMatch);
isMatch = (myTest.ToLower() == "The Hunt for Red October".ToLower());
You can do it like this Exemple if i only want to catch one time the letter minus a in a string and it can be check with myRegex.IsMatch()
^[^e][e]{1}[^e]$
how to make sure my string format must be like this :
locker_number=3,email=ucup#gmail.com,mobile_phone=091332771331,firstname=ucup
i want my string format `"key=value,"
how to make regex for check my string on ruby?
This regex will find what you're after.
\w+=.*?(,|$)
If you want to capture each pairing use
(\w+)=(.*?)(?:,|$)
http://rubular.com/r/A2ernIzQkq
The \w+ is one or more occurrences of a character a-z, 1-9, or an underscore. The .*? is everything until the first , or the end of the string ($). The pipe is or and the ?: tells the regex no to capture that part of the expression.
Per your comment it would be used in Ruby as such,
(/\w+=.*?(,|$)/ =~ my_string) == 0
You can use a regex like this:
\w+=.*?(,|$)
Working demo
You can use this code:
"<your string>" =~ /\w+=.*?(,|$)/
What about something like this? It's picky about the last element not ending with ,. But it doesn't enforce the need for no commas in the key or no equals in the value.
'locker_number=3,email=ucup#gmail.com,mobile_phone=091332771331,firstname=ucup' =~ /^([^=]+=[^,]+,)*([^=]+=[^,]+)$/
I am trying to use gsub to replace "?" and "." with empty space.
I realize that is a difference between gsub(".", "") and gsub(/./, ""), but I don't know what it is. Can Someone explain?
Also, gsub("?","") seems to work, and gsub(/?/,"") doesn't work.
How can we make gsub(/?/,"") work?
gsub("?", "") matches a literal ?, while gsub(/?/, "") uses regular expressions to find a match. And in regular expressions, the ? means that the previous character can be present either 0 or 1 times. In order to match a literal ?, you have to escapte it:
gsub(/\?/, "")
See also the ruby documentation about gsub
Finally as it mentioned above /reg/ represents regexp when "str" represents just a string. Your aim is to remove ? and . from a string. Regexp will do the job:
gsub(/[?.]/, '')
You can read more about ruby regexp here. In my example /[abc]/ will match single character a or b or c.
The former is to literally find "?" characters and replace them, while the latter is to find occurrences of 0 or 1 of a given character. ? has a special meaning for regular expressions, which you delimit using /.
Ok. Given the example of:
http://example.com/news/3226-some-post-title.html
I'm trying to get the 3226. This regexp: http://interaktywnie.com/newsy/(.*).html
doesn't seem to work. Please help.
Thanks.
You can just use:
/\/(\d+)-(.*)\.html$/
This will grab the digits (\d) after the '/' and put the digits into the first variable once it finds them.
A great place to test regular expression is http://rubular.com/.
You want this:
/http:\/\/example.com\/news\/(\d+)-.+\.html/
\d is any digit. Also, the following site is very useful for regular expressions in ruby:
http://www.rubular.com
"http://example.com/news/3226-some-post-title.html".split("/").last.to_i
Try this pattern:
/http:\/\/example\.com\/news\/(\d+)-.+\.html/
So:
match = /http:\/\/example\.com\/news\/(\d+)-.+\.html/.match("http://example.com/news/3226-some-post-title.html")
puts match[1]