Skip to content

Support named capture group #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 30, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ JavaScript implementation of [Simple Regex](https://simple-regex.com/) :tada::ta
[![codecov](https://codecov.io/gh/SimpleRegex/SRL-JavaScript/branch/master/graph/badge.svg)](https://codecov.io/gh/SimpleRegex/SRL-JavaScript)

> Because of the JavaScript regex engine, there is something different from [Simple Regex](https://simple-regex.com/)
- NOT support `as` to assign capture name.
- Support `as` to assign capture name with CODE but not regex engine.
- NOT support `if already had/if not already had`
- NO `first match` and NO `all lazy`, since in JavaScript `lazy` means non-greedy (matching the fewest possible characters).

Expand Down Expand Up @@ -46,10 +46,45 @@ Using [Webpack](http://webpack.github.io) and [babel-loader](https://github.com/
In SRL-JavaScript we apply `g` flag as default to follow the [Simple Regex](https://simple-regex.com/) "standard", so we provide more API to use regex conveniently.

- `isMatching` - Validate if the expression matches the given string.

```js
const query = new SRL('starts with letter twice')
query.isMatching(' aa') // false
query.isMatching('bbb') // true
```

- `getMatch` - Get first match of the given string, like run `regex.exec` once.

```js
const query = new SRL('capture (letter twice) as word whitespace')

query.getMatch('aa bb cc dd') // [ 'aa ', 'aa', index: 0, input: 'aa bb cc dd', word: 'aa' ]
```

- `getMatches` - Get all matches of the given string, like a loop to run `regex.exec`.

```js
const query = new SRL('capture (letter twice) as word whitespace')

query.getMatches('aa bb cc dd')
/**
* [
* [ 'aa ', 'aa', index: 0, input: 'aa bb cc dd', word: 'aa' ],
* [ 'bb ', 'bb', index: 3, input: 'aa bb cc dd', word: 'bb' ],
* [ 'cc ', 'cc', index: 6, input: 'aa bb cc dd', word: 'cc' ]
* ]
*/
```

- `removeModifier` - Remove specific flag.

```js
const query = new SRL('capture (letter twice) as word whitespace')

query.removeModifier('g')
query.get() // /([a-z]{2})\s/
```

## Development

First, clone repo and init submodule for test.
Expand Down
34 changes: 32 additions & 2 deletions lib/Builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ class Builder {

/** @var {string} _implodeString String to join with. */
this._implodeString = ''

/** @var {array} _captureNames Save capture names to map */
this._captureNames = []
}

/**********************************************************/
Expand Down Expand Up @@ -254,9 +257,14 @@ class Builder {
* Create capture group of given conditions.
*
* @param {Closure|Builder|string} condition Anonymous function with its Builder as a first parameter.
* @param {String} name
* @return {Builder}
*/
capture(conditions) {
capture(conditions, name) {
if (name) {
this._captureNames.push(name)
}

this._validateAndAddMethodType(METHOD_TYPE_GROUP, METHOD_TYPES_ALLOWED_FOR_CHARACTERS)

return this._addClosure(new Builder()._extends('(%s)'), conditions)
Expand Down Expand Up @@ -674,6 +682,26 @@ class Builder {
return result
}

/**
* Map capture index to name.
* When `exec` give the result like: [ 'aa ', 'aa', index: 0, input: 'aa bb cc dd' ]
* Then help to resolve to return: [ 'aa ', 'aa', index: 0, input: 'aa bb cc dd', [captureName]: 'aa' ]
*
* @param {object} result
* @return {object}
*/
_mapCaptureIndexToName(result) {
const names = this._captureNames

return Array.prototype.reduce.call(result.slice(1), (result, current, index) => {
if (names[index]) {
result[names[index]] = current || ''
}

return result
}, result)
}

/**
* Just like match in String, but reset lastIndex.
*
Expand All @@ -684,7 +712,8 @@ class Builder {
const regex = this.get()
const result = regex.exec(target)
regex.lastIndex = 0
return result

return this._mapCaptureIndexToName(result)
}

/**
Expand All @@ -697,6 +726,7 @@ class Builder {
let temp = null

while (temp = regex.exec(target)) {
temp = this._mapCaptureIndexToName(temp)
result.push(temp)
}
regex.lastIndex = 0
Expand Down
3 changes: 2 additions & 1 deletion lib/Language/Helpers/methodMatch.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const SimpleMethod = require('../Methods/SimpleMethod')
const ToMethod = require('../Methods/ToMethod')
const TimesMethod = require('../Methods/TimesMethod')
const AndMethod = require('../Methods/AndMethod')
const AsMethod = require('../Methods/AsMethod')

const SyntaxException = require('../../Exceptions/Syntax')

Expand Down Expand Up @@ -49,7 +50,7 @@ const mapper = {
'exactly': { 'class': TimesMethod, 'method': 'exactly' },
'at least': { 'class': TimesMethod, 'method': 'atLeast' },
'between': { 'class': AndMethod, 'method': 'between' },
'capture': { 'class': DefaultMethod, 'method': 'capture' }
'capture': { 'class': AsMethod, 'method': 'capture' }
}

/**
Expand Down
26 changes: 26 additions & 0 deletions lib/Language/Methods/AsMethod.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use strict'

const Method = require('./Method')

/**
* Method having simple parameter(s) ignoring "as".
*/
class AsMethod extends Method {
/**
* @inheritdoc
*/
setParameters(parameters) {
parameters = parameters.filter((parameter) => {
if (typeof parameter !== 'string') {
return true
}

const lower = parameter.toLowerCase()
return lower !== 'as'
})

return super.setParameters(parameters)
}
}

module.exports = AsMethod
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "srl",
"version": "0.2.0",
"version": "0.2.1",
"description": "Simple Regex Language",
"main": "lib/SRL.js",
"scripts": {
Expand Down
49 changes: 23 additions & 26 deletions test/rules-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ function buildData(lines) {
captures: {}
}
let inCapture = false
let captures = null // Remember captures' name and index.

lines.forEach((line) => {
if (line === '' || line.startsWith('#')) {
Expand All @@ -50,12 +49,7 @@ function buildData(lines) {
}

if (line.startsWith('srl: ')) {
captures = []

data.srl = line.substr(5).replace(/as\s+"([^"]+)"/g, (s, c) => {
captures.push(c)
return ''
})
data.srl = line.substr(5)
} else if (line.startsWith('match: "')) {
data.matches.push(applySpecialChars(line.slice(8, -1)))
} else if (line.startsWith('no match: "')) {
Expand All @@ -66,23 +60,15 @@ function buildData(lines) {
) {
inCapture = line.slice(13, -2)
data.captures[inCapture] = []
} else if (
inCapture &&
line.startsWith('-')
) {
} else if (inCapture && line.startsWith('-')) {
const split = line.substr(1).split(': ')
const index = captures.indexOf(split[1].trim())
let target = data.captures[inCapture][Number(split[0])]

if (!target) {
target = data.captures[inCapture][Number(split[0])] = []
}

if (index !== -1) {
target[index] = applySpecialChars(split[2].slice(1, -1))
} else {
target.push(applySpecialChars(split[2].slice(1, -1)))
}
target[split[1]] = applySpecialChars(split[2].slice(1, -1))
}
})

Expand Down Expand Up @@ -133,15 +119,26 @@ function runAssertions(data) {
)

matches.forEach((capture, index) => {
const result = Array.from(capture).slice(1).map((item) => {
return item === undefined ? '' : item
})

assert.deepEqual(
result,
expected[index],
`The capture group did not return the expected results for test ${test}.${getExpression(data.srl, query)}`
)
// const result = Array.from(capture).slice(1).map((item) => {
// return item === undefined ? '' : item
// })
const item = expected[index]

for (const key in item) {
if (typeof key === 'number') {
assert.equal(
capture[key + 1],
item[key],
`The capture group did not return the expected results for test ${test}.${getExpression(data.srl, query)}`
)
} else {
assert.equal(
capture[key],
item[key],
`The capture group did not return the expected results for test ${test}.${getExpression(data.srl, query)}`
)
}
}
})

assertionMade = true
Expand Down