Jump to content

basic regex


Michdd

Recommended Posts

Give us an explicit example of what you want. Will the two alphanumeric strings (e.g. namename) always be the same? Always surrounded with ".." and " ~"? Always have a single space between them? You say you want to match that entire string, but later say the ".." doesn't need to be matched, which is true?

 

Please fill in the following (change the two "changeme" parts to what you want).

 

$subject = 'changeme';
$pattern = 'we will figure this out';
preg_match($pattern, $subject, $match);
var_dump($match);
/*
  I want the output to be:
    changeme
*/

 

 

Link to comment
https://forums.phpfreaks.com/topic/181689-basic-regex/#findComment-958385
Share on other sites

Well, given the limited amount of information, here is an example of what I came up with:

 

$str = '..testing 123~';
preg_match('#(?:\.{2})?[a-z0-9]+\s[a-z0-9]+~$#i', $str, $match);
echo $match[0]; // Output: ..testing 123~

 

Of course, there are assumptions made here (due to lack of information):

a) The initial .. are grouped together and is optional (so in otherwords, it either has .., or no initial dots at all - so only starting with one dot will not be matched)

b) the two alpha numeric chunks are at least one or more characters each (as there is no specification on quantities)

c) I didn't use ^ at the beginning, as since the OP's attempt uses $ at the end, the assumption is that this aspect of the string only occurs at the end of a string, but is not the complete string in and of itself.

d) I used \s inbetween the alpha numeric chunks (to cover all whitespace characters, just in case... if it only requires a single literal space, you can replace \s with that instead).

 

@Michdd, regex is a very terse mini-language. As such, you have to include as much information as possible, otherwise people are left to make assumptions (and we all know what is said about assuming). When you used \D, this says "anything that is not a digit", but that will obviously mean it can encompass more than simply alpha numerics.

 

@Garethp, the use of \w in this case wouldn't be wise on account of 1, if not potentially 2 issues.. first, \w will match a-zA-Z0-9_ (note the underscore - which is not a character that the OP wishes to match). And of course, the second issue is locale... depending on the locale in question, \w might potentially match more than a-zA-Z0-9_

Link to comment
https://forums.phpfreaks.com/topic/181689-basic-regex/#findComment-958588
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.