given a string:
//foo.bar/baz/123/index.html
I am trying to match the number after baz, so long as it is not 123.
//foo.bar/baz/124/index.html (WOULD MATCH)
//foo.bar/baz/123/index.html (WOULD NOT MATCH)
How can I express this? I keep trying things like:
/baz\/d+^(123)/index/
but have not been successful. Any help is appreciated!
Use negative look-ahead to assert that there is not 123 after baz/. Then go on to match with \d+:
m~baz/(?!123\b)\d+/index~
In Perl, you can use different delimiter when your regex pattern already contains /, to avoid escaping them. Here I've used ~.
If the substring to not allow is fixed to be baz/123, you can also do it with index() function:
$str = "//foo.bar/baz/124/index.html";
$needle = "/baz/123/";
if (index($str, $needle) == -1) {
print "Match found\n";
}
Related
I cant remember what to use to return only a specific part of a string.
I have a string like this:-
$str = "return(me or not?)";
I want to get the word which is after (. In this example me will be my result. How can I do this?
I dont think substr is what I am looking for. as substr returns value based on the index you provided. which in this case i dont know the index, it can vary. All I know is that I want to return whatever is after "(" and before the space " ". The index positions will always be different there for i cant use substr(..).
This regular expression should do the trick. Since you didn't provide general rules but only an example it might need further changes though.
preg_match('/\((\S+)/', $input, $matches);
$matches[1] contains "me" then.
<?php
// Your input string
$string = "return(me or not?)";
// Pattern explanation:
// \( -- Match opening parentheses
// ([^\s]+) -- Capture at least one character that is not whitespace.
if (preg_match('/\(([^\s]+)/', $string, $matches) === 1)
// preg_match() returns 1 on success.
echo "Substring: {$matches[1]}";
else
// No match found, or bad regular expression.
echo 'No match found';
Result of capture group will be your result using this regex and preg_match().
$regex = '/\((\w+)/';
Check preg_match() for the working reference.
I'm making preg_match that allows 7-10 digits.
preg_match('/[0-9]{7,10}/', $studentID
Also another preg_match code that allows maximum of 20 alphabets with space and hyphen.
preg_match ('/^[a-zA-Z -]{,20}+$/i', $familyname
Both of these are not working.
You need to add anchors to the first regex the same way you used them with the second pattern, and you must define the lower bound for the limiting quantifier in the second pattern (say, 0 to 20):
$studentID = "1234567";
if (preg_match('/^[0-9]{7,10}$/', $studentID)) {
echo "$studentID matched!\n";
}
$familyname = "Pupkin";
if (preg_match ('/^[A-Z -]{0,20}$/i', $familyname)) {
echo "$familyname matched!";
}
See the PHP demo
Note that {0,20} and its possessive {0,20}+ version will work the same here since the pattern is not followed with other consuming subpatterns (so, no need to disable backtracking for the quantified subpattern).
Also, '/^[A-Z -]{0,20}$/i' is a very generic subpattern for surnames, you might want to further precise it. E.g., to disallow strings like all spaces or ---------, you may use '/^(?=.{0,20}$)[A-Z]+(?:[ -][A-Z]+)*$/i'.
This question already has answers here:
Regular expression to match a line that doesn't contain a word
(34 answers)
Closed 4 years ago.
if(preg_match("/" . $filter . "/i", $node)) {
echo $node;
}
This code filters a variable to decide whether to display it or not. An example entry for $filter would be "office" or "164(.*)976".
I would like to know whether there is a simple way to say: if $filter does not match in $node. In the form of a regular expression?
So... not an "if(!preg_match" but more of a $filter = "!office" or "!164(.*)976" but one that works?
This can be done if you definitely want to use a "negative regex" instead of simply inverting the result of the positive regex:
if(preg_match("/^(?:(?!" . $filter . ").)*$/i", $node)) {
echo $node;
}
will match a string if it doesn't contain the regex/substring in $filter.
Explanation: (taking office as our example string)
^ # Anchor the match at the start of the string
(?: # Try to match the following:
(?! # (unless it's possible to match
office # the text "office" at this point)
) # (end of negative lookahead),
. # Any character
)* # zero or more times
$ # until the end of the string
The (?!...) negative assertion is what you're looking for.
To exclude a certain string from appearing anywhere in the subject you can use this double assertion method:
preg_match('/(?=^((?!not_this).)+$) (......)/xs', $string);
It allows to specify an arbitrary (......) main regex still. But you could just leave that out, if you only want to forbid a string.
Answer number 2 by mario is the correct answer, and here is why:
First to answer the comment by Justin Morgan,
I'm curious, do you have any idea what the performance of this would
be as opposed to the !preg_match() approach? I'm not in a place where
I can test them both. – Justin Morgan Apr 19 '11 at 21:53
Consider the gate logic for a moment.
When to negate preg_match(): when looking for a match and you want the condition to be 1)true for the absence of the desired regex, or 2)false for the regex being present.
When to use negative assertion on the regex: when looking for a match and you want the condition to be true if the string ONLY matches the regex, and fail if anything else is found. This is necessary if you really need to test for undesireable characters while allowing ommission of permitted characters.
Negating the result of (preg_match() === 1) only tests if the regex is present. If 'bar' is required, and numbers aren't allowed, the following won't work:
if (preg_match('bar', 'foo2bar') === 1) {
echo "found 'bar'"; // but a number is here, so fail.
}
if (!pregmatch('[0-9]', 'foobar') === 1) {
echo "no numbers found"; // but didn't test for 'bar', so fail.
}
So, in order to really test multiple regexes, a beginner would test using multiple preg_match() calls... we know this is a very amateur way to do it.
So, the Op wants to test a string for possible regexes, but the conditional may only pass as true if the string contains at least one of them. For most simple cases, simply negating preg_match() will suffice, but for more complex or extensive regex patterns, it won't. I will use my situation for a more real-life scenario:
Say you want to have a user form for a person's name, particularly a last name. You want your system to accept all letters regardless of case and placement, accept hyphens, accept apostrophes, and exclude all other characters. We know that matching a regex for all undesired characters is the first thing we think of, but imagine you are supporting UTF-8... that's alot of characters! Your program will be nearly as big as the UTF-8 table just on a single line! I don't care what hardware you have, your server application has a finite limit on how long a command be, not to mention the limit of 200 parenthesized subpatterns, so the ENTIRE UTF-8 character table (minus [A-Z],[a-z],-,and ') is too long, never mind that the program itself will be HUGE!
Since we won't use an if (!preg_match('.#\\$\%... this can be quite long and impossible to evaluate... on a string to see if the string is bad, we should instead test the easier way, with an assertion negative lookaround on the regex, then negate the overall result using:
<?php
$string = "O'Reilly-Finlay";
if (preg_match('/?![a-z\'-]/i', $string) === 0) {
echo "the given string matched exclusively for regex pattern";
// should not work on error, since preg_match returns false, which is not an int (we tested for identity, not equality)
} else {
echo "the given string did not match exclusively to the regex pattern";
}
?>
If we only looked for the regex [a-z\'-]/i , all we say is "match string if it contains ANY of those things", so bad characters aren't tested. If we negated at the function, we say "return false if we find a match that contained any of these things". This isn't right either, so we need to say "return false if we match ANYTHING not in the regex", which is done with lookahead. I know the bells are going off in someone's head, and they are thinking wildcard expansion style... no, lookahead doesn't do this, it just does negation on each match, and continues. So, it checks first character for regex, if it matches, it moves on until it finds a non-match or the end. After it finishes, everything that was found to not match the regex is returned to the match array, or simply returns 1. In short, assert negative on regex 'a' is the opposite of matching regex 'b', where 'b' contains EVERYTHING ELSE not matchable by 'a'. Great for when 'b' would be ungodly extensive.
Note: if my regex has an error in it, I apologize... I have been using Lua for the last few months, so I may be mixing my regex rules. Otherwise, the '?!' is proper lookahead syntax for PHP.
I'm trying to understand what's wrong with this regex pattern:
'/^[a-z0-9-_\.]*[a-z0-9]+[a-z0-9-_\.]*{4,20}$/i'
What I'm trying to do is to validate the username. Allowed chars are alphanumeric, dash, underscore, and dot. The restriction I'm trying to implement is to have at least one alphanumeric character so the user will not be allowed to have a nickname like this one: _-_.
The function I'm using right now is:
function validate($pattern, $string){
return (bool) preg_match($pattern, $string);
}
Thanks.
EDIT
As #mario said, yes,t here is a problem with *{4,20}.
What I tried to do now is to add ( ) but this isn't working as excepted:
'/^([a-z0-9-_\.]*[a-z0-9]+[a-z0-9-_\.]*){4,20}$/i'
Now it matches 'aa--aa' but it doesn't match 'aa--' and '--aa'.
Any other suggestions?
EDIT
Maybe someone wants to deny not nice looking usernames like "_..-a".
This regex will deny to have consecutive non alphanumeric chars:
/^(?=.{4,20}$)[a-z0-9]{0,1}([a-z0-9._-][a-z0-9]+)*[a-z0-9.-_]{0,1}$/i
In this case _-this-is-me-_ will not match, but _this-is-me_ will match.
Have a nice day and thanks to all :)
Don't try to cram it all into one regex. Make your life simpler and use a two step-approach:
return (bool)
preg_match('/^[a-z0-9_.-]{4,20}$/', $s) && preg_match('/\w/', $s);
The mistake in your regex probably was the mixup of * and {n,m}. You can have only one of those quantifiers, not *{4,20} both after another.
Very well, here is the cumbersome solution to what you want:
preg_match('/^(?=.{4})(?!.{21})[\w.-]*[a-z][\w-.]*$/i', $s)
The assertions assert the length, and the second part ensures that at least one letter is present.
Try this one instead:
'/[a-z0-9-_\.]*[a-z0-9]{1,20}[a-z0-9-_\.]*$/i'
Its probably just a matter if finetuning, you could try something like this:
if (preg_match('/^[a-zA-Z0-9]+[_.-]{0,1}[a-zA-Z0-9]+$/m', $subject)) {
# Successful match
} else {
# Match attempt failed
}
Matches:
a_b <- you might not want this.
ysername
Username
1254_2367
fg3123as
Non-Matches:
l__asfg
AHA_ar3f!
sAD_ASF_#"#T_
"#%"&#"E
__-.asd
username
1___
Non-matches you might want to be matches:
1_5_2
this_is_my_name
It is clear to me that you should split this into two checks!
Firstly check that they are using all valid characters. If they're not, then you can tell them that they are using invalid characters.
Then check that they have at least one alpha-numeric character. If they're not, then you can tell them that they must.
Two distinct advantages here: more meaningful feedback to the user and cleaner code to read and maintain.
Here is a simple, single regex solution (verbose):
$re = '/ # Match password having at least one alphanum.
^ # Anchor to start of string.
(?=.*?[A-Za-z0-9]) # At least one alphanum.
[\w\-.]{4,20} # Match from 4 to 20 valid chars.
\z # Anchor to end of string.
/x';
In Action (short form):
function validate($string){
$re = '/^(?=.*?[A-Za-z0-9])[\w\-.]{4,20}\z/';
return (bool) preg_match($re, $string);
}
Try this:
^[a-zA-Z][-\w.]{0,22}([a-zA-Z\d]|(?<![-.])_)$
From related question: Create one RegEx to validate a username
^[A-Za-z][A-Za-z0-9]*(?=.{3,31}$)[a-z0-9]{0,1}([a-z0-9._-][a-z0-9]+)*[a-z0-9.-_]{0,1}$
This will Validate the username
start with an alpha
accept underscore dash and dots
no spaces allowed
Why don't you make it simpler like this?
^[a-zA-Z][a-zA-Z0-9\._-]{3,9}
First letter should be Alphabetical.
then followed by character or symbols you allowed
length of the word should be between 4,10 (as explicitly force the first word)
I want to find the first matching string in a very very long text. I know I can use preg_grep() and take the first element of the returned array. But it is not efficient to do it like that if I only need the first match (or I know there is exactly only one match in advance). Any suggestion?
preg_match() ?
preg_match() returns the number of
times pattern matches. That will be
either 0 times (no match) or 1 time
because preg_match() will stop
searching after the first match.
preg_match_all() on the contrary will
continue until it reaches the end of
subject. preg_match() returns FALSE if
an error occurred.
Here's an example of how you can do it:
$string = 'A01B1/00asdqwe';
$pattern = '~^[A-Z][0-9][0-9][A-Z][0-9]+~';
if (preg_match($pattern, $string, $match) ) {
echo "We have matched: $match[0]\n";
} else {
echo "Not matched\n";
}
You can try print_r($match) to check the array structure and test your regex.
Side note on regex:
The tilde ~ in the regex are just delimiters needed to wrap around
the pattern.
The caret ^ denote that we are matching from the start
of the string (optional)
The plus + denotes that we can have one or
more integers that follow. (So that A01B1, A01B12, A01B123 will also
be matched.