Skip to content

Instantly share code, notes, and snippets.

@zeffii
Forked from anonymous/string_formatting.ck
Created November 17, 2013 20:40
Show Gist options
  • Save zeffii/7518014 to your computer and use it in GitHub Desktop.
Save zeffii/7518014 to your computer and use it in GitHub Desktop.
//
//
// A walk-through and demo of string formatting
//
// Nov 2013.
//
// Perl-compatible syntax can also be used for patterns.
// http://www.cs.tut.fi/~jkorpela/perl/regexp.html
RegEx r; // make a regex object
/*
- RegEx.replace(string pat, string repl, string str)
Replace the first instance of pat in str with repl, returning the
result.
*/
<<< "Demo 1: RegEx.replace" >>>;
"this 34-56-23 will contain 345-243-345 rewrites" => string fill_str;
["line", "several"] @=> string repl[];
for(0 => int s; s<repl.cap(); s++){
r.replace("([0-9]{2,3}-?){3}", repl[s], fill_str) => fill_str;
}
<<< fill_str >>> ;
/*
- RegEx.replaceAll(string pat, string repl, string str)
Replace all instances of pat in str with repl, returning the
result.
*/
<<< "Demo 2: RegEx.replaceAll" >>>;
"this %s is no greater than this %s" => string fill_str2;
r.replaceAll("%s", "20", fill_str2) => fill_str2;
<<< fill_str2 >>> ;
/*
- RegEx.match(string pattern, string str)
Return true if match for pattern is found in str, false otherwise
\d is not a recognized excape sequence
*/
<<< "Demo 3: RegEx.match" >>>;
"this is a short demo string 0x3000h a match" => string fill_str3;
if (r.match("0x[0-9]{4}h", fill_str3)){
<<< "yes found a match 1" >>>;
}
// fails :(
// if (r.match("0x\d{4}h", fill_str3)){
// <<< "yes found a match 2" >>>;
// }
/*
- RegEx.match(string pattern, string str, string matches[])
Same as above, but return the match and sub-patterns in matches
matches[0] is the entire matched pattern, matches[1] is the first
sub-pattern (if any), and so on.
*/
// etc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment