Same question has been asked here:
How to pass a regular expression as a function parameter, but I can't get it work by JSNI.
This is the string of the regular expression that will be used to test email:
"^(([^<>()[\]\\.,;:\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,}))$"
and if putting it to firebug execute like this:
/^(([^<>()[\]\\.,;:\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,}))$"/.test("test#domain.com")
it will give what I want,but If wrapping it to a JSNI method:
private native String reEmail()/-*{
return "^(([^<>()[\]\\.,;:\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,}))$";
}-*/;
then passing it to the function:
private native boolean validate(String value, String regexp)/-*{
//escape special characters
var re=regexp.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').replace(/\x08/g, '\\x08');
return new RegExp(re,'g').test(value)
}-*/;
like this:
validate("test#domain.com",reEmail());
It will give me false.Please tell what mistakes I have made,thanks.
Why do you want to use JSNI for regular expressions?. Gwt already has classes to deal with them.
I would use com.google.gwt.regexp.shared.Regexp that features like Javascript's RegExp.
Using gwt com.google.gwt.regexp.shared.RegExp you have many advantages:
don't have to deal with JSNI, saving syntax errors.
make your code testable since RegExp can be used in JVM.
let the implementation escape strings or whatever.
performance would be the same
Your code could be like:
// Note that you have to double escape \
RegExp r = RegExp.compile("^(([^<>()[\\]\\\\.,;:\\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,}))$");
if (r.test("test#domain.com")) {
} else {
}
Anyway if you continue wanting to do in your way, to make your code work, you should escape your string before returning to java instead of in the place you are trying to do, also your JSNI block syntax is incorrect, note /*-{}-*/ instead of /-*{}*-/. And you don't need the 'g' flag.
validate("test#domain.com",reEmail());
private native String reEmail() /*-{
return "^(([^<>()[\\]\\\\.,;:\\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,}))$";
}-*/;
private native boolean validate(String value, String regexp)/*-{
return new RegExp(regexp).test(value)
}-*/;
Related
In Perl, we can do this
s/pattern/func($1)/e
Is there any convenient function that does the same thing with PCRE2, like
::pcre2_substitute_with_callback(
re, // the compiled pattern
pcuSubject, ccuSubject, // the subject and its length
PCRE2_SUBSTITUTE_GLOBAL, // the substitute options
matches,
NULL, // the match context
[](PCRE2_SPTR pcuMatched)->PCRE2_SPTR{ // the callback
return "replacement";
},
pcuResult, &ccuResult
);
Thanks.
No, I think that there is no such convenience in pcre2. See the wrapper below though.
However, I believe that the replacement string for the call to pcre2_substitute can be prepared without any particular restrictions. (I cannot test now.) The use of escape character ($) for capturing groups or pattern items is clearly specified but I don't see why one couldn't use that in a function/callback to form the replacement string.
That can then be wrapped in a method with a desired signature.
Some more documentation from pcre2api is at Creating a new string with substitutions
There is a C++ wrapper JPCRE2. It uses the replace method of RegexReplace for this purpose. However, about half-way through the main page it also informs us that
There's another replace function (jp::RegexReplace::nreplace()) that takes a MatchEvaluator with a callback function. It's required when you have to create the replacement strings dynamically according to some criteria.
The class jp::MatchEvaluator implements several constructor overloads to take different callback functions.
The page continues with a full example for usage of jp::RegexReplace::nreplace().
More detailed examples are offered in a test file in the distribution.
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).
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 am working with smartgwt since three months.
I have encountered a problem with the specific method of the string class.
It seems that the matches never works, even with the simplest one:
String regex = "CEDD";
String input = "CEDD";
input.matches(regex);
this will always returns false. Such piece of code is within a class extending the smartgwt Layout class, and therefore got converted to js and used in front end.
The same fragment obviously works when used in a simple java main standalone class.
Could you point out what to investigate to solve this problem ?
thanks
It looks like GWT doesn't support normal Java regular expressions (i.e. doesn't support Pattern, Matcher and classes/methods that use it.
There is a RegExp class that provides those features, however.
I'm new to regular expressions and would like to use one to search through our source control to find text within a block of code that follows a particular enum value. I.e.:
/(\/{2}\#debug)(.|\s)*?(\/{2}\#end-debug).*/
var junk = dontWantThis if (junk) {dont want this} if ( **myEnumValue** ) **{ var yes = iWantToFindThis if (true) { var yes2 = iWantThisToo } }**
var junk2 = dontWantThis if (junk) {dont want this}
var stuff = dontWantThis if (junk) {dont want this} if ( enumValue ) { wantToFindThis }
var stuff = iDontWantThis if (junk) {iDontWantThisEither}
I know I can use (\{(/?[^\>]+)\}) to find if blocks, but I only want the first encompassing block of code that follows the enum value I'm looking for. I've also notice that using (\{(/?[^\>]+)\}) gives me the first { and last }, it doesn't group the subsequent {}.
Thank you!
Tim
Regexps simply can't handle this kind of stuff. For this you'll need a parser and scanner.
As others hint at, it's mathematically impossible to do with with regular expressions (at least in general; you might be able to get it to work if you have highly specialized cases). Try using a combination of lex and awk to get the desired results if you want to stick with standard Unix tools, or just go to Perl, Python, Ruby, etc. and build up the lexical parsing you need.
While nesting is a problem, you could use backtracking and lookahead to effectively count your matching braces or quotes. This is not strictly part of a regular expression but has been added to many regex libraries, such as the one in .NET, perl, and java; probably more. I wouldn't recommend that you go this route, as you should find it easier to lexically parse this. But if you do try this as a quick fix, absolutely collect a few test cases and run them through regexbuddy or expresso.