Using javascript regex to parse strings starting with "$" and other conditions -


this difficult regex wrap head around. i'd words start $. conditions are:

  • string must start $ , preceding character must either beginning of string or space.

  • if $ followed ", in between "" must captured. both quotes must present or nothing captured.

  • "" used capturing more 1 word

  • $ not match anything

some examples:

  • bob gave jane $4

    ["4"] captured

  • $"10 thousand dollars" lot more $1 , $-3

    ["10 thousand dollars", "1", "-3"] captured

  • bob paid $590 $micro$oft $and" wa$ reimbursed $nine

    ["590", "micro$oft", "nine"] captured

  • alice says $"hello $world!"

    ["hello $world!"] captured

  • $ yup$

    nothing captured

i tried playing around horrible. look-aheads make tricky.

function parse(text) {      var re = /(\s|^)\$(?:"([^"]*)"|([^\s"]+)(?!\s))/g;      re.lastindex = 0;      var result = [];      var match;      while (match = re.exec(text)) {          result.push(match[2] || match[3]);      }      return result;  }    var tests = [    'bob gave jane $4',    '$"10 thousand dollars" lot more $1 , $-3',    'bob paid $590 $micro$oft $and" wa$ reimbursed $nine',    'alice says $"hello $world!"',    '$ yup$'  ];    $('<table>').append([    $('<thead>').append([      $('<tr>').append([        $('<th>').text('test'),        $('<th>').text('captures')      ])    ]),    $('<tbody>').append(      $.map(tests, function (test) {        var result = parse(test);        return $('<tr>').append([          $('<td>').append([            $('<code>').text(test)          ]),          $('<td>').append([            $('<code>').text(json.stringify(result))          ])        ]);      })    )  ]).appendto('#output23');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div id="output23"></div>


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -