Monday 17 March 2014

RegExp in Twine

A RegExp is a regular expression (also called a RegEx), a special kind of string for matching against other strings.

Match

 A simple example of their use in a game might be to ask the player to type in an answer to a question, and to test if the answer is correct. you might try this:

if ($input == 'dragon') 

What if the player types "DRAGON" or "dragons" of " dragon"? None of these will match, as they are not exactly the same. Using a RegExp allows as to match the input against a pattern:

if ($input.match(/dragon/i)) 

Here we use the match method to compare the string against a pattern. the pattern itself has slashes at each, and a modifier, i, after the second slash. The i indicates that the pattern matching will be case insensitive, so this will match "Dragon". As long as the sequence "dragon" appears in the input, a match will be found.

Replace

The string class also support the replace method, which you can use to replace one piece of text with another. This also supports RegExps. Here is an example that will replace "story" with "tale":

s.replace(/story/, 'tale')

However, it will only replace the first occurance; it is usually better to add a modifier, g, to make is global. in this version, every occurance of story will be replaced.

s.replace(/story/g, 'tale')

Wild cards

The power of RegExp is that you can use wildcards to match against a string that is somewhat like what you expect. In this example, the \w will match any alphanumeric character (including underscore!). The thus sign indicates there can be any number of them, but at least one (use * to match against none or more).

/the \w+ story/
  the great story
  the 1st story

You can also match against alternatives:

/stor(y|ies)/
  story
  stories

Capture groups

You can also grab some text from the pattern and use it. You surround the text you want to capture in brackets in the RegExp, then use it in the replacement as a dollar followed by a number.

s.replace(//the (\w+) story//g, 'the $1 tale')
  the great story -> the great tale

Start and End

Often you will want to match against the start of the text and the end. The start can be matched against \A or ^, the end against \Z or $. This example will match only if this is the entire text - no more and no less.

/^The great story$/

Finally

RegExp is a big topi and this is really only scratching the surface, but is hopefully enough to give a feel for what it is. A couple of links with lists of codes you can use:

http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

No comments:

Post a Comment