Jump to content

Regular Expressions Help


SupraCharger
Go to solution Solved by SupraCharger,

Recommended Posts

Hi all,

I'm trying to get this regular expression to work, but I keep getting a error:

 

Warning: preg_match(): Unknown modifier ']'

 

$pattern = '/^(C:\\)[A-Za-z0-9\040\.\-\\\/]$/';

 

$pattern = '/^(C:\\)[[:alnum:]\040\.\-\\\/]$/'; // Also tried this pattern
        
if (preg_match ( $pattern, trim ($_POST['contfile']) ))

 

Thanx for your help,

Andrew

Link to comment
Share on other sites

The ASCII table contains quite a few more characters than what's available on the keyboard, including non-printable characters such as BELL, NULL etc. Not to mention the fact that the extended ASCII table really isn't in use today, as other character sets have taken its place. Most notably UTF-8, which allows for (just about) every type of alphabet to be used.

 

However, if you want all of the printable characters from the basic ASCII table, it's quite easy to set up a range using the hexadecimal values from the ASCII table.

$matchASCII = "[\x20-\x7f]";

Edited by Christian F.
Link to comment
Share on other sites

Is it [[:ascii:]] ?

Nearly, but not quite. It sounds more like you want to use [[:print:]]

 

[[:ascii:]] is the equivalent of [\x00-\x7F] (find these numbers under "Hx" on asciitable.com). As you will see, this includes characters that aren't available on a keyboard.

 

However, if you want all of the printable characters from the basic ASCII table, it's quite easy to set up a range using the hexadecimal values from the ASCII table.

$matchASCII = "[\x20-\x7f]";

A better end of the range would be \x7E, since \x7F is the "delete" character. Then, the character class would be the same as [[:print:]].

 

SupraCharger, does the "print" class cover the characters that you are interested in? I only ask because most keyboards have keys which provide other characters (for example, horizontal tab or the enter/return key) and many keyboards can have other non-ASCII characters too (for example, the euro symbol or accented characters). There's no reason why you can't extend the character class to include characters other than in [:print:].

Link to comment
Share on other sites

Thank you Christian F. you really know your stuff,

 

I still can't seem to get this pattern right from the top of the thread.

 

requinix,

    The pattern did not work. There where no errors but it didn't validate correctly. I Think '\\\\' in '(C:\\\\)' is for double quotes.

 

 

$pattern = '/^(C:\\)[[:print:]]$/'; 
 

 

 

For Validating: C:\Users\Owner\Desktop\old_databases.docx

 

Thanx,

A.

Edited by SupraCharger
Link to comment
Share on other sites

 

 

$pattern = '/^(C:\\)[[:print:]]$/'; 
 
 

For Validating: C:\Users\Owner\Desktop\old_databases.docx

 

 

That won't work. The \\ becomes \ inside the string and the pattern is
/^(C:\)[[:print:]]$/
resulting in an unmatched (. '\\\\' will turn into \\ and a literal backslash.
Link to comment
Share on other sites

There are two key issues with ^(C:\\)[[:print:]]$

  • The (C:\\) is not quite doing what you think. Echo out the $pattern variable and you will see the regex that is trying to be executed. It starts like ^(C:\)

     

    Notice how there is only one slash there? Regex understands \) as matching a literal right-parenthesis ()) character. Since there is then no matching right-parenthesis to pair up with the left-parenthesis immediately before C; the regex engine will complain at you (with "Compilation failed: missing )"). To properly match the C:\ that you want, you need to be mindful of how PHP strings interpret backslashes and how the regex engine does too. You want the resulting regex executed by the regex engine to be like (C:\\) but to write that in string-form in PHP you would need a string like '(C:\\\\)' — as requinix already pointed out (twice now).

     

  • Next, the character class [[:print:]] only matches a single character. In order to cater for more than one character, a quantifier is needed. In this case you probably want + to say, "one or more printable characters". This is nice and short, but you could also specify a min/max number of characters rather than "one or more" by using the {x,y} style quantifier which matches between x and y consecutive occurrences of whatever is being quantified (in your case, the character class).
In summary, something that might be more useful could look like: $pattern = '/^(C:\\\\)[[:print:]]+$/D';

 

P.S. You'll see I've added a D — see if you can figure out why. :shy:

Edited by salathe
Link to comment
Share on other sites

No, you need to use four backslashes to check for one in the string. Two backslashes will add one unescaped backslash into the string, which the RegExp engine then interprets as an escape-character. To escape it in the RegExp engine as well, you need to have two slashes in the RegExp itself as well. Which means, inserting another two into the PHP string.

 

Anyway, the reason you're not seeing anything is because [] defines a character group. Which matches one character, out of the possible ones listed in said group. Which means your RegExp will only validate a one-letter path.

C:\t
To make it match more, you'll need to add a quantifier. + being the most probable one, if you want at least one character in the path, but don't have an upper limit.

 

That said, your RegExp is not going to properly validate a path, as you are allowing way too many characters. Characters which the OS does not allow to be used in directory and/or file names.

Link to comment
Share on other sites

Thanx all for clearing that up for me, the mash of Chars in regular expressions gives me tunnel vision. But I forgot the regex engine stips the escape char  '\' out.

 

salathe,

   Is it because you don't want a didget extension ex: ( .213 ).

  Wait I forgot about the " $ ", I have no idea?

 

Thanx,

A.

Edited by SupraCharger
Link to comment
Share on other sites

I think this pattern that I wrote would work very well for Files the have double quotation marks around them.

 

Ex:   "C:\Users\Owner\Desktop\old_databases.docx"

 

 

$pattern = '/.*(C:\\\\)([[:alnum:]_*-*\040*]+\\\\)*[[:alnum:]_*-*\040*]+(\.)[[:alpha:]]{2,4}.*$/';
 

 

 

Andrew

 

P.S. While you guys did an amazing job explaining the concept, I think this post answers my first question the best.

Edited by SupraCharger
Link to comment
Share on other sites

(This one is Safer)

I think this pattern that I wrote would work very well for Files the have double quotation marks around them.

 

Ex:   "C:\Users\Owner\Desktop\old_databases.docx"

 

 

$pattern = '/.{0,1}(C:\\\\)([[:alnum:]_*-*\040*]+\\\\)*[[:alnum:]_*-*\040*]+(\.)[[:alpha:]]{2,4}.{0,1}$/';
 

 

 

Andrew

 

P.S. While you guys did an amazing job explaining the concept, I think this post answers my first question the best.

Link to comment
Share on other sites

So the following is a happy file path? (I'm only teasing, but hopefully it proves a point) :shy:

SQUIRE TRELAWNEY, Dr. Livesey, and the rest of these gentlemen having asked me to write down the whole particulars about Treasure Island, from the beginning to the end, keeping nothing back but the bearings of the island, and that only because there is still treasure not yet lifted, I take up my pen in the year of grace 17__ and go back to the time when my father kept the Admiral Benbow inn and the brown old seaman with the sabre cut first took up his lodging under our roof. I remember him as if it were yesterday, as he came plodding to the inn door, his sea-chest following behind him in a hand-barrow—a tall, strong, heavy, nut-brown man, his tarry pigtail falling over the shoulder of his soiled blue coat, his hands ragged and scarred, with black, broken nails, and the sabre cut across one cheek, a dirty, livid white. I remember him looking round the cover and whistling to himself as he did so, and then breaking out in that old sea-song that he sang so often afterwards: "Fifteen men on the dead man's chest— Yo-ho-ho, and a bottle of rum!" in the high, old tottering voice that seemed to have been tuned and broken at the capstan bars. Then he rapped on the door with a bit of stick like a handspike that he carried, and when my father appeared, called roughly for a glass of rum. This, when it was brought to him, he drank slowly, like a connoisseur, lingering on the taste and still looking about him at the cliffs and up at our signboard. "This is a handy cove," says he at length; "and a pleasant sittyated grog-shop. Much company, mate?" My father told him no, very little company, the more was the pity. "Well, then," said he, "this is the berth for me. Here you, matey," he cried to the man who trundled the barrow; "bring up alongside and help up my chest. I'll stay here a bit," he continued. "I'm a plain man; rum and bacon and eggs is what I want, and that head up there for to watch ships off. What you mought call me? You mought call me captain. Oh, I see what you're at—there"; and he threw down three or four gold pieces on the threshold. "You can tell me when I've worked through that," says he, looking as fierce as a commander. And indeed bad as his clothes were and coarsely as he spoke, he had none of the appearance of a man who sailed before the mast, but seemed like a mate or skipper accustomed to be obeyed or to strike. The man who came with the barrow told us the mail had set him down the morning before at the Royal George, that he had inquired what inns there were along the coast, and hearing ours well spoken of, I suppose, and described as lonely, had chosen it from the others for his place of residence. And that was all we could learn of our guest. He was a very silent man by custom. All day he hung round the cove or upon the cliffs with a brass telescope; all evening he sat in a corner of the parlour next the fire and drank rum and water very strong. Mostly he would not speak when spoken to, only look up sudden and fierce and blow through his nose like a fog-horn; and we and the people who came about our house soon learned to let him be. Every day when he came back from his stroll he would ask if any seafaring men had gone by along the road. At first we thought it was the want of company of his own kind that made him ask this question, but at last we began to see he was desirous to avoid them. When a seaman did put up at the Admiral Benbow (as now and then some did, making by the coast road for Bristol) he would look in at him through the curtained door before he entered the parlour; and he was always sure to be as silent as a mouse when any such was present. For me, at least, there was no secret about the matter, for I was, in a way, a sharer in his alarms. He had taken me aside one day and promised me a silver fourpenny on the first of every month if I would only keep my "weather-eye open for a seafaring man with one leg" and let him know the moment he appeared. Often enough when the first of the month came round and I applied to him for my wage, he would only blow through his nose at me and stare me down, but before the week was out he was sure to think better of it, bring me my four-penny piece, and repeat his orders to look out for "the seafaring man with one leg." How that personage haunted my dreams, I need scarcely tell you. On stormy nights, when the wind shook the four corners of the house and the surf roared along the cove and up the cliffs, I would see him in a thousand forms, and with a thousand diabolical expressions. Now the leg would be cut off at the knee, now at the hip; now he was a monstrous kind of a creature who had never had but the one leg, and that in the middle of his body. To see him leap and run and pursue me over hedge and ditch was the worst of nightmares. And altogether I paid pretty dear for my monthly fourpenny piece, in the shape of these abominable fancies. But though I was so terrified by the idea of the seafaring man with one leg, I was far less afraid of the captain himself than anybody else who knew him. There were nights when he took a deal more rum and water than his head would carry; and then he would sometimes sit and sing his wicked, old, wild sea-songs, minding nobody; but sometimes he would call for glasses round and force all the trembling company to listen to his stories or bear a chorus to his singing. Often I have heard the house shaking with "Yo-ho-ho, and a bottle of rum," all the neighbours joining in for dear life, with the fear of death upon them, and each singing louder than the other to avoid remark. For in these fits he was the most overriding companion ever known; he would slap his hand on the table for silence all round; he would fly up in a passion of anger at a question, or sometimes because none was put, and so he judged the company was not following his story. Nor would he allow anyone to leave the inn till he had drunk himself sleepy and reeled off to bed. His stories were what frightened people worst of all. Dreadful stories they were—about hanging, and walking the plank, and storms at sea, and the Dry Tortugas, and wild deeds and places on the Spanish Main. By his own account he must have lived his life among some of the wickedest men that God ever allowed upon the sea, and the language in which he told these stories shocked our plain country people almost as much as the crimes that he described. My father was always saying the inn would be ruined, for people would soon cease coming there to be tyrannized over and put down, and sent shivering to their beds; but I really believe his presence did us good. People were frightened at the time, but on looking back they rather liked it; it was a fine excitement in a quiet country life, and there was even a party of the younger men who pretended to admire him, calling him a "true sea-dog" and a "real old salt" and such like names, and saying there was the sort of man that made England terrible at sea. In one way, indeed, he bade fair to ruin us, for he kept on staying week after week, and at last month after month, so that all the money had been long exhausted, and still my father never plucked up the heart to insist on having more. If ever he mentioned it, the captain blew through his nose so loudly that you might say he roared, and stared my poor father out of the room. I have seen him wringing his hands after such a rebuff, and I am sure the annoyance and the terror he lived in must have greatly hastened his early and unhappy death. All the time he lived with us the captain made no change whatever in his dress but to buy some stockings from a hawker. One of the cocks of his hat having fallen down, he let it hang from that day forth, though it was a great annoyance when it blew. I remember the appearance of his coat, which he patched himself upstairs in his room, and which, before the end, was nothing but patches. He never wrote or received a letter, and he never spoke with any but the neighbours, and with these, for the most part, only when drunk on rum. The great sea-chest none of us had ever seen open. He was only once crossed, and that was towards the end, when my poor father was far gone in a decline that took him off. Dr. Livesey came late one afternoon to see the patient, took a bit of dinner from my mother, and went into the parlour to smoke a pipe until his horse should come down from the hamlet, for we had no stabling at the old Benbow. I followed him in, and I remember observing the contrast the neat, bright doctor, with his powder as white as snow and his bright, black eyes and pleasant manners, made with the coltish country folk, and above all, with that filthy, heavy, bleared scarecrow of a pirate of ours, sitting, far gone in rum, with his arms on the table. Suddenly he—the captain, that is—began to pipe up his eternal song: "Fifteen men on the dead man's chest— Yo-ho-ho, and a bottle of rum! Drink and the devil had done for the rest— Yo-ho-ho, and a bottle of rum!" At first I had supposed "the dead man's chest" to be that identical big box of his upstairs in the front room, and the thought had been mingled in my nightmares with that of the one-legged seafaring man. But by this time we had all long ceased to pay any particular notice to the song; it was new, that night, to nobody but Dr. Livesey, and on him I observed it did not produce an agreeable effect, for he looked up for a moment quite angrily before he went on with his talk to old Taylor, the gardener, on a new cure for the rheumatics. In the meantime, the captain gradually brightened up at his own music, and at last flapped his hand upon the table before him in a way we all knew to mean silence. The voices stopped at once, all but Dr. Livesey's; C:\ he went on as before speaking clear and kind and drawing briskly at his pipe between every word or two.end

P.S. An example of the above "file path" being tested against the latest regex: http://codepad.viper-7.com/kGwbB2
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.