使用javascript正则表达式解析以“$”和其他条件开头的字符串

时间:2014-12-16 07:18:46

标签: javascript regex

这是一个困难的正则表达式。我希望得到所有以$开头的单词。条件是:

  • 字符串必须以$开头,前面的字符必须是字符串的开头或空格。

  • 如果$后跟",则必须捕获""之间的所有内容。两个引号必须存在或没有捕获任何内容。

  • ""仅用于捕获多个单词

  • $本身不匹配任何内容

一些例子:

  • Bob gave Jane $4

    [" 4"]抓获

  • $"10 Thousand Dollars" is a lot more than $1 and $-3

    [" 10万美元"," 1"," -3"]被捕获

  • Bob paid $590 to $Micro$oft $and" wa$ reimbursed $Nine

    [" 590"," Micro $ oft"," Nine"]被捕获

  • Alice says $"Hello $World!"

    [" Hello $ World!"]捕获

  • $ Yup$

    没有捕获任何内容

我试过playing around,但这太可怕了。前瞻使得这非常棘手。

1 个答案:

答案 0 :(得分:0)



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" is a lot more than $1 and $-3',
  'Bob paid $590 to $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');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output23"></div>
&#13;
&#13;
&#13;