Fold All / Expand All

2016年2月20日 星期六

VerbalExpressions - Regular Expressions made easy

竟然有這種神奇的東西@@
把 Regular Expression 改用更多話的方式來寫,以下列出 JS, PHP, Python 的範例

JavaScript

// Create an example of how to test for correctly formed URLs
var tester = VerEx()
    .startOfLine()
    .then('http')
    .maybe('s')
    .then('://')
    .maybe('www.')
    .anythingBut(' ')
    .endOfLine();

// Create an example URL
var testMe = 'https://www.google.com';

// Use RegExp object's native test() function
if (tester.test(testMe)) {
    alert('We have a correct URL '); // This output will fire}
} else {
    alert('The URL is incorrect');
}

console.log(tester); // Outputs the actual expression used: /^(http)(s)?(\:\/\/)(www\.)?([^\ ]*)$/

PHP

$regex = new VerbalExpressions;

$regex  ->startOfLine()
        ->then("http")
        ->maybe("s")
        ->then("://")
        ->maybe("www.")
        ->anythingBut(" ")
        ->endOfLine();

if($regex->test("https://github.com/"))
    echo "valid url";
else
    echo "invalid url";

if (preg_match($regex, 'http://github.com')) {
    echo 'valid url';
} else {
    echo 'invalid url';
}

echo "<pre>". $regex->getRegex() ."</pre>";

echo $regex ->clean(array("modifiers" => "m", "replaceLimit" => 4))
            ->find(' ')
            ->replace("This is a small test http://somesite.com and some more text.", "-");

Python

# Create an example of how to test for correctly formed URLs
verbal_expression = VerEx()
tester = (verbal_expression.
            start_of_line().
            find('http').
            maybe('s').
            find('://').
            maybe('www.').
            anything_but(' ').
            end_of_line()
)

# Create an example URL
test_url = "https://www.google.com"

# Test if the URL is valid
if tester.match(test_url):
    print "Valid URL"

#Print the generated regex
print tester.source() # => ^(http)(s)?(\:\/\/)(www\.)?([^\ ]*)$

沒有留言: