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).
Related
I need to use the .replace() function to replace abc123="NULL" with abc123=NULL but only when NULL is the only word between the quotation marks, otherwise, leave it as it is.
Struggling to find the correct combination of escpaped characters to make this work.
Note: there are no quotation marks at the beginning or end of this data value i.e. it is not abc123="NULL" that I am working with. It is explicitly abc123="NULL"
Can any one manage this?
Edit: I'm using a privately written development environment that builds using Java.
Edit: If I could it would look like this x.replace(="NULL", =NULL) BUT I need to escape the = and quotation marks. Baring in mind I can only do this replacement if the word is NULL and is not any other word.
Not sure to well understand but, is that what you want:
var x = 'abc="NULL"';
x = x.replace('="NULL"', '=NULL');
console.log(x);
I would like to know if either/both of these two scenarios are possible in Lua:
I have a string that looks like such: some_value=averylongintegervalue
Say I know there are exactly 21 characters after the = sign in the string, is there a short way to replace the string averylongintegervalue with my own? (i.e. a simpler way than typing out: string.gsub("some_value=averylongintegervalue", "some_value=.....................", "some_value=anewintegervalue")
Say we edit the original string to look like such: some_value=averylongintegervalue&
Assuming we do not know how many characters is after the = sign, is there a way to replace the string in between the some_value= and the &?
I know this is an oddly specific question but I often find myself needing to perform similar tasks using regex and would like to know how it would be done in Lua using pattern-matching.
Yes, you can use something like the following (%1 refers to the first capture in the pattern, which in this case captures some_value=):
local str = ("some_value=averylongintegervalue"):gsub("(some_value=)[^&]+", "%1replaced")
This should assign some_value=replaced.
Do you know if it is also possible to replace every character between the = and & with a single character repeated (such as a * symbol repeated 21 times instead of a constant string like replaced)?
Yes, but you need to use a function:
local str = ("some_value=averylongintegervalue")
:gsub("(some_value=)([^&]+)", function(a,b) return a..("#"):rep(#b) end)
This will assign some_value=#####################. If you need to limit this to just one replacement, then add ,1 as the last parameter to gsub (as Wiktor suggested in the comment).
This I probably a dumb question but it beats me.
The same thing in Python works perfectly, although in AS3 doesn't.
var s:String = "123456";
trace(s.split(/../gm));
Expecting this as array: ['12','34','56']
But instead I get: [,,]
I have experimented various regexr patterns but none split into 2-char batches.
Any ideas / solutions ?
You're using the split command, which means the string will be divided into an array of values using the regular expression .. to match the delimiters. These delimiters are then not included in the output.
I think you want to do something like s.match(/../g). See also this link for more information about .match
Good day. I can't seem to find an example of how use the TRegExpr component to do a simple replace of invalid characters. For example i have a string = 'abcdeg3fghijk'; and i want to replace all the characters that are invalid such as the numerial '3', how would process this with TRegExpr to replace all invalid characters. My intention is learn how to use the TRegExpr to build a simple url cleaner/validator.
procedure TForm1.Button3Click(Sender: TObject);
var
RegExp: TRegExpr;
astr:string;
begin
astr:='h"ttp://ww"w.msn."com~~~';
// I want to clean the string to remove all non valid chars
//this is where I am lost
RegExp:=TRegExpr.Create;
try
RegExp.Expression:=RegExpression;
finally
RegExp.Free;
end;
end;
Judging from the commments and the question edit, you are trying to work out how to perform a replacement using a regex. The function you need is TRegEx.Replace.
There are lots of overloads. The simplest to use are the class functions. For example:
NewValue := TRegEx.Replace(OldValue, '3', '4');
will replace all occurrences of 3 with 4.
Or if you want to use the instance method approach, do it like this:
var
RegEx: TRegEx;
....
RegEx.Create('3');
NewValue := RegEx.Replace(OldValue, '4');
Remember that TRegEx is a record, a value type. There's no Free to call and no need for try/finally. I personally regard Create as very badly named. I would have preferred Initialize if I had been designing the TRegEx type.
Using the instance method approach allows the expression to be compiled and that speeds up performance for repeated matching of the same expression to different input data. I don't know whether that would matter for you. If not then use the class function interface which is simpler to use.
You'll obviously extend this to use a useful regex for your replacement!
The documentation for the PCRE regex flavour that Delphi uses is here: http://www.regular-expressions.info/pcre.html
I have a txt file with content
$NETS
P3V3_AUX_LGATE; PQ6.8 PU37.2
U335_PIN1; R3328.1 U335.1
$END
need to be updated in this format, and save back to another txt file
$NETS
'P3V3_AUX_LGATE'; PQ6.8 PU37.2
'U335_PIN1'; R3328.1 U335.1
$END
NOTE: number of lines may go up to 10,000 lines
My current solution is to read the txt file line by line, detect the presence of the ";" and newline character and do the changes.
Right now i have a variable that holds ALL the lines, is there other way something like Replace via RegEx to do the changes without looping thru each line, this way i can readily print the result
and follow up question, which one is more efficient?
Try
ResultString = Regex.Replace(SubjectString, "^([^;\r\n]+);", "'$1';", RegexOptions.Multiline)
on your multiline string.
This will find any string (length one or more) at the start of a line up until the first semicolon if there is one and replace it with its quoted equivalent.
It should be more efficient than looping through the string line by line as you're doing now, but if you're in doubt, you'd have to profile it.
You could probably find all the matches using something like \w+; but I don't know how you'd be able to do a replace on that using Regex.Replace to add the 's but keep the original match.
However, if you already have it as one variable, you don't have to read the file again, either you could make your code find all ;s and then find the previous newline for each, or you could use a String.Split on newlines to split the variable you've already got into lines.
And if you want to get it back to one variable you can just use String.Join.
Personally I'd normally use the String.Split (and possibly the String.Join if needed) method, since I think that would make the code easy to read.
I would say Yes! this can be done with Regular expressions. Make sure you got the "multiline" option turned on and craft your regular expression using some capture groups to ease the work.
I can however say this will NOT be the optimal one. Since you mention the amount of lines you could be processing, it seems 'resource wise' smarter to use a streaming approach instead of the in memory approach.
Taking the Regex approach (and this took 15 mins so please don't think this is an optimal solution, just prove it would work)
private static Regex matcher = new Regex(#"^\$NETS\r\n(?<entrytitle>.[^;]*);\s*(?<entryrest>.*)\r\n(?<entrytitle2>.[^;]*);\s*(?<entryrest2>.*)\r\n\$END\r\n", RegexOptions.Compiled | RegexOptions.Multiline);
static void Main(string[] args)
{
string newString = matcher.Replace(ExampleFileContent, new MatchEvaluator(evaluator));
}
static string evaluator(Match m)
{
return String.Format("$NETS\r\n'{0}'; {1}\r\n'{2}'; {3}\r\n$END\r\n",
m.Groups["entrytitle"].Value,
m.Groups["entryrest"].Value,
m.Groups["entrytitle2"].Value,
m.Groups["entryrest2"].Value);
}
Hope this helps,