Read Integer within a String - ruby-1.8

I need to somehow read an integer within a string. The string will be as follows;
GAME_SWITCH(476)
And I need to read the 476 part. Note, it won't be 476 each time, but it will be "GAME_SWITCH(...)" each time. I've tried using the .delete methods to delete "GAME_SWITCH(" and ")", but that has no effect for some reason. I just want the "476" which I can then convert to an integer.
Furthermore, is there also a way to check if the string adheres to those rules? if the string is just "foobar" it returns false?
I am using Ruby 1.8.1
Thanks a lot!

You can solve the problem with regular expressions for example:
if m = str.match(/^GAME_SWITCH\((\d+)\)$/)
m[1].to_i
else
false
end

Try something like this
my_string.scan(/\d+/)[0].to_i

Related

Regular expression to extract either integer or string from JSON

I am working in an environment without a JSON parser, so I am using regular expressions to parse some JSON. The value I'm looking to isolate may be either a string or an integer.
For instance
Entry1
{"Product_ID":455233, "Product_Name":"Entry One"}
Entry2
{"Product_ID":"455233-5", "Product_Name":"Entry One"}
I have been attempting to create a single regex pattern to extract the Product_ID whether it is a string or an integer.
I can successfully extract both results with separate patterns using look around with either (?<=Product_ID":")(.*?)(?=") or (?<=Product_ID":)(.*?)(?=,)
however since I don't know which one I will need ahead of time I would like a one size fits all.
I have tried to use [^"] in the pattern however I just cant seem to piece it together
I expect to receive 455233-5 and 455233 but currently I receive "455233-5"
(?<="Product_ID"\s*:\s*"?)[^"]+(?="?\s*,)
, try it here.

Regular Expression for a range between

I checked around but didn't find a regular expression that was suitable. I'm trying to match on only numbers (8-32) and tried a few combinations that were unsuccessful including (Regex regex = new Regex("[8-9]|[10-29]\\d",RegexOptions.IgnoreCase | RegexOptions.Singleline);). This only got me up to 8-29 and then I got lost.
I know there is a better and easier way if I just create an if statement, but I'll never learn anything doing it that way. :-)
Any help would be greatly appreciated.
Using a regex for checking whether a number is in a range is a bad idea. Regex only cares about what characters are in the string, not what the value of each character represents. The regex engine doesn't know that 2 in 23 actually means 20. To it, it's the same as any other 2.
You might be able to write a highly complex regex to do that, but don't.
Assuming you are using C#, just convert the string to an integer like this
var integer = Convert.ToInt32(yourString);
then check if it is in range with an if statement:
if (integer >= 8 && integer <= 32) {
}
If your number is a part of a larger string, then you can use regex to extract the number out, convert it to an int, and check it with an if.
As a reference for regex testing with explanations, I would suggest you https://regexr.com/
And for your need : 8-32, you will want a pattern like
[8-9]|[1-2][0-9]|3[0-2]
So that you will get 8 or 9 or every number between 10 and 29 or 30 to 32

How to replace characters in string Erlang?

I have this piece of code that gets sessionid, make it a string, and then create a set with key as e.g. {{1401,873063,143916},<0.16443.0>} in redis. I'm trying replace { characters in this session with letter "a".
OldSessionID= io_lib:format("~p",[OldSession#session.sid]),
StringForOldSessionID = lists:flatten(OldSessionID),
ejabberd_redis:cmd([["SADD", StringForSessionID, StringForUserInfo]]);
I've tried this:
re:replace(N,"{","a",[global,{return,list}]).
Is this a good way of doing this? I read that regexp in Erlang is not a advised way of doing things.
Your solution works, and if you are comfortable with it, you should keep it.
On my side I prefer list comprehension : [case X of ${ -> $a; _ -> X end || X <- StringForOldSessionID ]. (just because I don't have to check the function documentation :o)
re:replace(N,"{","a",[global,{return,list}]).
Is this a good way of doing this? I read that regexp in Erlang is not
a advised way of doing things.
According to official documentation:
2.5 Myth: Strings are slow
Actually, string handling could be slow if done improperly. In Erlang, you'll have to think a little more about how the strings are used and choose an appropriate representation and use the re module instead of the obsolete regexp module if you are going to use regular expressions.
So, either you use re for strings, or:
leave { behind(using pattern matching)
if, say, N is {{1401,873063,143916},<0.16443.0>}, then
{{A,B,C},Pid} = N
And then format A,B,C,Pid into string.
Since Erlang OTP 20.0 you can use string:replace/3 function from string module.
string:replace/3 - replaces SearchPattern in String with Replacement. 3rd function parameter indicates whether the leading, the trailing or all encounters of SearchPattern are to be replaced.
string:replace(Input, "{", "a", all).

How do you extract text matching a pattern in XPATH?

I have data that looks like this:
<value>v13772 #FBst0451145:w<up>1118</up>; P{GD3649}v13772#
v13773 #FBst0451146:w<up>1118</up>; P{GD3649}v13773#</value>
How can I process this string in XPATH to extract any and all #FBst####### numbers?
I know of the xpath matches() function... but that only returns true or false. No good if I want the matching string. I've searched around but cannot find a satisfactory answer to this problem, which is probably really common.
Thanks!
In addition to the good answer by Michael Kay, if you want to use only the replace() function, then use:
replace(.,'.*?(#FBst\d+).*','$1')
The result is:
#FBst0451145
#FBst0451146
And if you only want the numbers from the above result, use:
replace(replace(.,'.*?(#FBst\d+).*','$1'),
'[^0-9]+', ' ')
This produces:
0451145 0451146
I Assume you can also use XQuery. The get_matches() function from the FunctX module should work for you. Download the file which supports your version of XQuery. Then import the module whenever you need its functionality.
import module namespace functx = "http://www.functx.com" at "functx-1.0-doc-2007-01.xq";
functx:get-matches(string-join(//text()),'xyz')
Try
tokenize(value, '[^0-9]+')
which should return the sequence of tokens separated by sequences of non-digits.
With help from Dimitre, a working regex is:
replace(.,'.*?(#FBst\d+).*','$1 ','m')
Although it doesn't work unless a newline separates each target string, it will do for now.
Thanks everyone!

Regular Expression to allow an empty string or a string with specific length

Hi I am having trouble trying to create a regex that will allow me to have the field empty or a string with length 9 if populated.
The current regex im using is: ^[0-9]{9}
Which works if the field is mandatory, however we have a new requirement that this can also be empty. I've tried ^[0-9]{0|9} but obviously that doesnt work.
Thanks in advance
^(|[0-9]{9})$
Should do the trick.
Edit: But seriously; do what #Felix Kling suggests in a comment: test the string via a .length property, .equals("") or the like.