Regex doesn't find a match with a pattern - html

In a C# project, Regex is behaving weirdly for me.
I have this method:
string RegTest()
{
string HTML = "<input type=\"hidden\" name=\"authenticity_token\" value=\"d27956cca6b75db4d8dd502d0569dd246455131c\">";
Regex AuthRegex = new Regex(#"name=""authenticity_token"" value=""([A-Ba-b0-9/-]+)""");
string Auth = AuthRegex.Match(HTML).Value;
return Auth;
}
For a reason I don't understand at all, the Regex doesn't find any match with this pattern. It just returns "".
How can I fix this?

The problem is:
[A-Ba-b0-9/-]+
What character ranges (x-y) basically do is get a set of all characters in between. In other words, a-b = all letters between a and b, aka only a and b. However,
d27956cca6b75db4d8dd502d0569dd246455131c
looks like a hex. Therefore, you should use
[A-Fa-f0-9-]+
instead.

Related

Checking for special character in JSON string with Everit and regex [duplicate]

What is the regular expression (in JavaScript if it matters) to only match if the text is an exact match? That is, there should be no extra characters at other end of the string.
For example, if I'm trying to match for abc, then 1abc1, 1abc, and abc1 would not match.
Use the start and end delimiters: ^abc$
It depends. You could
string.match(/^abc$/)
But that would not match the following string: 'the first 3 letters of the alphabet are abc. not abc123'
I think you would want to use \b (word boundaries):
var str = 'the first 3 letters of the alphabet are abc. not abc123';
var pat = /\b(abc)\b/g;
console.log(str.match(pat));
Live example: http://jsfiddle.net/uu5VJ/
If the former solution works for you, I would advise against using it.
That means you may have something like the following:
var strs = ['abc', 'abc1', 'abc2']
for (var i = 0; i < strs.length; i++) {
if (strs[i] == 'abc') {
//do something
}
else {
//do something else
}
}
While you could use
if (str[i].match(/^abc$/g)) {
//do something
}
It would be considerably more resource-intensive. For me, a general rule of thumb is for a simple string comparison use a conditional expression, for a more dynamic pattern use a regular expression.
More on JavaScript regexes: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
"^" For the begining of the line "$" for the end of it. Eg.:
var re = /^abc$/;
Would match "abc" but not "1abc" or "abc1". You can learn more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Perl if statement, If value = nothing do statement if value = something do statement

I am trying to insert a value from a text box into a SQL table. Although when I leave the text box blank it is adding a blank value which then causes the rest of the form functions to not work.
I want the if statement to check if $animal is blank do nothing. And if $animal has something in it, then to perform the insert into the table.
I am not quite sure what to put where I have put.
if ($animal = " ") {
}
else
if ($animal = "???") {
insertTable("INSERT INTO $table(name) VALUE ('".$animal."')");
Line 24 - 27 is this
sub insertTable {
$statement = shift (#_);
$dbh->do($statement);
} # sub
Perl uses scalar variables, which are quite versatile little things. One of the gotchas with them is that their 'truthiness' isn't always obvious.
If you test a scalar with a Boolean test it will be false if:
It's undefined.
It's an empty string.
It's the number 0.
It's the string "0".
(Arrays test as false if they're undefined or have no elements.)
So the correct answer would be - either used defined to check if the value is defined. Or use a regular expression to pattern match a 'valid' value.
E.g.
if ( $animal =~ m/\w+/ ) {
# Do something
}
\w+ is the Perl regular expression for saying 'one or more word characters' which is alphanumeric and underscore. So your empty string, whitespace only string, or undefined string will all not match this pattern.
Quite a few problems here. Addressing the worst of them:
You're using = which is for assignment, not comparison. Use == to compare numbers and eq to compare strings.
You're comparing your variable to a single space. It's very unlikely that you'll get a single space character in $animal. You'll want to do something either far simpler (if ($animal) { ... }) or more complex (perhaps if ($animal =~ /\w/) { ... }).
You are interpolating user input directly into SQL which you then run against your database. This leads to SQL injection attacks. Far better to use a bind point in your SQL.
In Perl there isn't a null value, only an undefined!
if (defined $value)
{
# Do that
}
else
{
# Do this
}

PHP force a var to have a certain type

This may be a stupid question but I might aswell as it :)
is there away to force
$tel1 = '05';// string
settype($tel1,'string');
$tel1 = 06;//either throw error, or convert it to string automatically.
var_dump($tel1);//(string [2]) 05
The above code is of the top of my head so might not be accurate but I need to keep a variable as a string not numeric, because of some silly thing I have done, now my phone numbers lose the leading 0s :-(
n I cn't rewrite it because it will mess up with other numeric types,b4 u ask it was an automated service for db to check if it was a numeric value or not,
UPDATE
This is the problem
function escape($str){
if(is_numeric($str)){
return $str;
}else{
return "'".mysql_real_escape_string($str).'\'';
}
}
$tel1 = "06";
$sql = 'SELECT * FROM blabla WHERE id = '.escape($tel1).'';
//above is same as below
$sql = 'SELECT * FROM blabla WHERE id = 06 ';
I can't change anything inside the scape function because other inputes thruout the website are using this function, I dont wanna mess their validations.
Your use of is_numeric tests for numeric content, not an integer type. But then you take a variable called $str which implies you want it to be a string.
Perhaps use:
function escape($val) {
if (is_numeric($val) && !is_string($val)) {
return $val;
}
else{
return "'" . mysql_real_escape_string($val) . '\'';
}
}
Now strings will be escaped and quoted, but not if they contain only numeric content.
you can do something like:
$string = (string) $int;
or use a function
$string = strval($int);
You can't force a variable to a specific type in the global scope.
You can force Arrays and Objects in a function.
function getElementsByClassName(DOMNode $parentElement, Array $classNames) {
...
}
If you pass an object that is not an instantiation of DOMNode (or a subclass), or if you don't pass an Array as the second argument, you'll get an error.
You can of course cast any variable, e.g. (string) $tel1.
You shouldn't be treating phone numbers as Ints anyway, because of leading zeroes and possible parenthesis and dashes. Also, once your telephone number is an Int, it won't know its 0 padding anymore because it will be discarded, so casting it back won't give you the original String.
To cast a variable you can use something like:
$i = 1;
$s = (string) $i;
Depending on the db adaptor you might not be able to detect the type being returned from the database. I believe it's PDO that returns everything (even INT values) as strings.
The number_format() function may be of use to you too.
If you declare a variable as:
$var = 06;
it immediately becomes 6 without leading zero because leading zero when it comes to integers is meaningless and therefore it's cut out.
In other words, your variable has to be created as string, which is what you probably deduced yourself.
Quick fix would be the following: you can add another parameter to your escape() function.
For example:
function escape($str, $force_str = false)
{
if($force_str)
{
// do your conversion, the rest of the site will by default pass false so nothing will be broken
}
}
As alex said, start by making sure the phone number is never converted from string to int in your own code. Then, you need to make sure it will not be converted when sent to your SQL DB.
It ought to work if you do it this way:
$sql = "SELECT * FROM blabla WHERE id = '" . mysql_real_escape_string($tel1) . "'";
This is the same as
$sql = "SELECT * FROM blabla WHERE id = '06'";

Extracting an integer from a string?

How do I extract the numbers out of a string like this:
$1.50
Everything but the currency symbol. Or from something like this:
rofl1.50lmao
Just asking if there's an existing function that I'm not a aware of.
There is no builtin function in AS3 for that. A simple RegExp like this one should help you :
/[0-9]+.?[0-9]*/
This is an example, and should be refactored depending your context.
Here is a more precise RegEx from Gunslinger47:
/-?\d*\.?\d+([eE]\d+)?/
This is "plain" JavaScript, but FWIW:
justNumsAndDots = "rofl1.50lmao".replace(/[^\d.]/g,"") // -> "1.50" (string)
asIntegral = parseInt("0" + justNumsAndDots, 10) // -> 1 (number)
asNumber = parseFloat("0" + justNumsAndDots) // -> 1.5 (number)
asTwoDecimalPlaces = (2 + asNumber).toFixed(2) // -> "3.50" (string)
Notes:
Doesn't take localization into account.
Radix (base-10) is passed to parseInt to avoid potential octal conversion (not sure if this "issue" plagues AS).
"0" is added to the start of justNumsAndDots so parseInt/parseFloat will never return a NaN here. (e.g. parseFloat(".") -> NaN, parseFloat("0.") -> 0). If NaN's are desired, alter to suite.
Input like "rofl1.chopter50lolz" will be stripped to "1.50", it might be over-greedy, depending.
Adapt to AS as necessary.
Happy coding.
As far as I know, no. You can parse every character against an array of valid characters, or use regexp.

String.replace() function to parse XML string so that it can be displayed in HTML

I have a XML string which needs to be displayed within HTML. I understand the first thing needed to be done here is to convert all '<' and '>' into '& lt;' and '& gt;' (ignore the space after & sign). This is what I am doing to replace '<' -
regExp = new RegExp("/</g");
xmlString = xmlString.replace(regExp, '& lt;');
xmlString does not change.
Also, trace(regExp.test("<")); prints false.
What is wrong here?
replace returns a new string, it doesn't modify the old one. So if you want to overwrite the old you have to do the following:
xmlString = xmlString.replace(regExp, '<');
Or if you don't want to overwrite the old one, just store the result in a new variable.
var newString = xmlString.replace(regExp, '<');
The issue is the way you create your RegExp object.
Because your using the RegExp constructor, don't include the / characters:
regExp = new RegExp("<", "g");
or use / as a shortcut:
regExp = /</g;
See this page for more details: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/RegExp.html