Coder Social home page Coder Social logo

verbalexpressions / jsverbalexpressions Goto Github PK

View Code? Open in Web Editor NEW
12.2K 12.2K 511.0 3.18 MB

JavaScript Regular expressions made easy

Home Page: http://verbalexpressions.github.io/JSVerbalExpressions/

License: MIT License

JavaScript 100.00%
javascript-regular-expressions verbalexpressions

jsverbalexpressions's Introduction

Build Status

PHPVerbalExpressions

VerbalExpressions is a PHP library that helps to construct hard regular expressions.

Installation

The project supports Composer so you have to install Composer first, before project setup.

$ composer require  verbalexpressions/php-verbal-expressions:dev-master

Examples

<?php
// some tests
require './vendor/autoload.php';
use VerbalExpressions\PHPVerbalExpressions\VerbalExpressions;

$regex = new VerbalExpressions();

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


if ($regex->test("http://github.com")) {
    echo "valid url". '<br>';
} else {
    echo "invalid url". '<br>';
}

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.", "-");

More examples are available in the following files:

Business readable language expression definition

$definition = 'start, then "http", maybe "s", then "://", maybe "www.", anything but " ", end';
$regex = new VerbalExpressionsScenario($definition);

Methods list

Name Description Usage
add add values to the expression add('abc')
startOfLine mark expression with ^ startOfLine(false)
endOfLine mark the expression with $ endOfLine()
then add a string to the expression add('foo')
find alias for then find('foo')
maybe define a string that might appear once or not maybe('.com')
anything accept any string anything()
anythingBut accept any string but the specified char anythingBut(',')
something accept any non-empty string something()
somethingBut anything non-empty except for these chars somethingBut('a')
replace shorthand for preg_replace() replace($source, $val)
lineBreak match \r \n lineBreak()
br shorthand for lineBreak br()
tab match tabs \t tab()
word match \w+ word()
anyOf any of the listed chars anyOf('abc')
any shorthand for anyOf any('abc')
range adds a range to the expression range(a,z,0,9)
withAnyCase match case default case sensitive withAnyCase()
stopAtFirst toggles the g modifiers stopAtFirst()
addModifier add a modifier addModifier('g')
removeModifier remove a mofier removeModifier('g')
searchOneLine Toggles m modifier searchOneLine()
multiple adds the multiple modifier multiple('*')
_or wraps the expression in an or with the provided value _or('bar')
limit adds char limit limit(1,3)
test performs a preg_match test('[email protected]')

For all the above method (except test) you could use the VerbalExpressionsScenario.

Other Implementations

You can see an up to date list of all ports on VerbalExpressions.github.io.

Building the project and running the tests

The project supports Composer so you have to install Composer first before project setup.

curl -sS https://getcomposer.org/installer | php
php composer.phar install --dev
ln -s vendor/phpunit/phpunit/phpunit.php phpunit
./phpunit

jsverbalexpressions's People

Contributors

akalicki avatar alexishevia avatar daquirm avatar dependabot-preview[bot] avatar dependabot[bot] avatar dfvalero avatar go-oleg avatar gprasant avatar jcputney avatar jehna avatar kishikawakatsumi avatar leonardosouza avatar mackenza avatar malixsys avatar mihai-vlc avatar ptrstpp950 avatar readmecritic avatar ronfroy avatar ryan-endacott avatar ryasmi avatar shabda avatar shakyshane avatar signpostmarv avatar softwarespot avatar subzey avatar tombyrer avatar v2e4lisp avatar vincemtnz avatar xsawyerx avatar xuefeng-zhu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsverbalexpressions's Issues

Logo

We need a logo for this organisation any suggestions/contributions ?

anythingBut string?

Is there any current usage for supporting anythingBut('sequence')? Eg, saying "match anything but this string" instead of "match anything but these characters"?

Port to other languages

Given the relatively small size of the VerbalExpression class and its general usefulness I feel it would be easy and helpful to port it to other languages. I see that @putneyj is working on a Java version, and I'd be willing to port it to C++ / PHP as well if you think it's a good idea.

Predefined expressions

Good expressions to use to catch URLs, emails and XML.
Or even other most-commonly-used regular expressions

Make it a web service ?

Hi Jehna,

This API is a great idea but I think it should be a web service to help developers to understand or generate complicated regexp.
I think it will be more useful than loading the JS in our webpages to be able to write human-readable regexp.

My two cents,

Regards,

Move to organistion

Since we started an organisation here https://github.com/VerbalExpressions and this repo is the most popular i propose to move it to the organisation so people can have easy access to the other repos available there.
The idea here is to have them all in one place so we can maintain them better.

Resultant expression

Do you think there could be use in a function that returns the resultant expression? Happy to do this if there are folks wanting it.

Usage example?

This looks like a brilliant idea at first but then I've encountered some difficulties immediately trying to convert a very basic Regex to Verex:

string.split(/\s(.+)?/, 2)

How do I rewrite this in Verex?

Also, an online sandbox that display Verex and the equivalent Regex side-by-side would be really helpful.

Objective-C/Cocoa Port

Hi,

I'd like to make an Objective-C port using NSRegularExpression. Anybody else interested in joining me?

Port to FreeBASIC

I have ported this to the FreeBASIC language, http://freebasic.net. FreeBASIC doesn't have native regex but can use C libraries (being close to C itself makes this easy) so this implementation uses PCRE. I expanded from an earlier version of my code that used posix regex so other regex engines are possible and I'd be happy to build support for that if users want it.

Translate to normal RegEx

How can I translate this form RegEx to normal?
May I use this library as interpreter to normal Regular Expression?

i.e.:
Write -> VerbalExpression
Get - > RegEx

Cheat sheet

Make cheat sheet out of the documentation

Performance tests needed

Even if the regexes produced are optimized, it'll still be worth doing. If possible, a guide for how to write perf tests would be helpful, too.

Are there any recommended ways to do perf testing in the repo or is externally on jsperf the only good option?

LineBreak - a better match

It seems to me that, for completeness, a better match for linebreak would be:
(?:\r\n|\r|\n)
And if only JS had atomic groups then it'd be this instead:
(?>\r\n|\r|\n)

re-use of tester results in incorrect output

verbalExpr = require("verbal-expressions")

endOfOutputTester = verbalExpr()
      .startOfLine()
      .then("www")

test1 = "www"
console.log(endOfOutputTester.test(test1))
console.log(endOfOutputTester.test(test1))
console.log(endOfOutputTester.test(test1))
console.log(endOfOutputTester.test(test1))
console.log(endOfOutputTester.test(test1))

the output is

true
false
true
false
true

using version 0.1.0

Add git tag!!!

git tag v0.1.2
git push origin master --tags

that way we can install this with bower

Plans on PyPI packaging?

I would very much like to use the python implementation of VerbalExpressions but I am not going to copy-paste the source into my sources in order to use it.
Could you please consider uploading it as a module onto the python package index?

I'd go ahead and do it myself, but this would basically prevent you from using the name.

Regards,
Max

Email format expression

I have implemented for email address validation, but no success.

var emailValidate = VerEx()
.startOfLine()
.anythingBut(" ")
.then("@")
.anythingBut(" ")
.then(".")
.anythingBut(" ")
.endOfLine();

if(!emailValidate.test("user@example."))alert("Incorrect");
else alert("Correct");

I am getting correct result with "user@example." email.

Go implementation

Hi,

Very interessed by your project, I made a Go implementation. Can you open a repo in you organisation ?

anythingBut function uses * when users expect +

As seen in #16, there is some confusion as to the actual functionality of the anythingBut() method. The function is currently implemented using the regex * operator, meaning that anythingBut() will match any sequence other than the characters given, even if that is an empty sequence. But some people don't expect an empty sequence to be a possible result.

I think the best thing to do would be to split it into two functions, one that uses * and one that uses +. They'd have to be appropriately named so that it's clear in what context each should be used.

Thoughts?

Functions usable in others

For example, if I want to search for "anything but linebreak" that would be a lot prettier if I could do that this way:

.anythingBut( this.br() )

Shouldn't be hard, I think I can do the JS part, ideas?

Update: VerEx().br() works, so I'll close it.

Implementation rules

Hi,
Working on Go implementation, I checked other languages implementation to follow rules.

This is difficult for us... To my side I switch in Cpp and Python implementation + yours (javascript, that is not in organization list) to understand what to implement.

For example, "multiple" method is not easy to understand reading JS and PHP implementations wich makes something very different.

BTW I guess multiple implementation is not "as it should be"...

Is it possible to create a repo where we can work on implementation doc ?

Multiple() implementation

I guess my Go implementation gives more control... you can see

http://godoc.org/github.com/VerbalExpressions/GoVerbalExpressions#VerbalExpression.Multiple

I give possibilities:

multiple(value, min, max)

This is not complicated to do ans it's (I guess) efficient.

Edit, here are the calls and what they can do:

// get "foo" at least one time
v.Multiple("foo")
v.Multiple("foo", 1)

// get "foo" 0 or more times
v.Multiple("foo", 0)

//get "foo" 0 or 1 times
v.Multiple("foo", 0, 1)

// get "foo" 0 to 10 times
v.Multiple("foo",0 ,10)

//get "foo" at least 10 times
v.Multiple("foo", 10)

//get "foo" exactly 10 times
v.Multiple("foo", 10, 10)

//get "foo" from 1 to 10 times
v.Multiple("foo", 1, 10)

Specifying names for capture groups

Following up on go-oleg's comment on issue #17: I tried adding his suggestion to add names to capture groups. I've got something working but wanted to run my ideas past others first. Please note that this would be the first time I've ever contributed anything on github. Here's what I came up with:
beginCapture(group): The group parameter is optional. If it's an integer (or a string of all digits), the value must match the actual group number that would be assigned to the group (in JavaScript this would be the index into the array returned by regexp.exec()) or else it's an error. If it's some other string, it's a group name that's assigned to the capture group.
endCapture(group): The group parameter is optional; if present it must match the parameter of the corresponding beginCapture().
groupNumberFor(group): would be used after the expression is built to return the index number. E.g.
var tester = VerEx()
.startOfLine()
.beginCapture( "one" )
.then( "http" )
.maybe( "s" )
.endCapture( "one" )
.then( "://" )
.maybe( "www." )
.anythingBut( " " )
.endOfLine();
var testMe = "https://www.google.com";
var a = tester.exec(testMe);
a [tester.groupNumberFor( "one" )]) -- returns "https"

I'm not sure how to handle the errors, though (mismatched group name or number). I've made them throw exceptions, but if this is the wrong way to go I can change it. Again, I'm really new at this so any suggestions are appreciated.

the results should be true

var VerEx = require("verbal-expressions");
var tester = VerEx()
    .startOfLine()
    .then( "http" )
    .maybe( "s" )
    .then( "://" )
    .maybe( "www." )
    .anythingBut( " " )
    .endOfLine();
// Create an example URL
var testMe = "https://www.google.com";
console.log( tester.test( testMe )  );  // true
console.log( tester.test( testMe )  );  // false
console.log( tester.test( testMe )  );  //true
console.log( tester.test( testMe )  ); //false

the results should be true

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.