0

In javascript I use pattern:

/"(?:""|[^"])*"|[-+]?\b[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?(?!&)\b/g

to extract some values from text.

var pattern = /"(?:""|[^"])*"|(?!\n)[-+]?\b[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?(?!&)\b/g;
var input = "Amx = 1000: Hmx = 200\nTotal = Amx + Hmx + _\n3000\nComment = \"Payment completed\"\nWarning_\n1 Task1 is completed\n2 Task2 is uncompleted\n\n";
var values = input.match(pattern);
for (var i in values)
  console.log(values[i]);

Input:

Amx = 1000: Hmx = 200
Total = Amx + Hmx + _
3000
Comment = "Payment completed"
Warning_
1 Task1 is completed
2 Task2 is uncompleted

Log:

  1. 1000
  2. 200
  3. 3000
  4. Payment completed"
  5. 1 (unexpected)
  6. 2 (unexpected)

But the result include some unexpected values (1, 2) beginning with \n. How can I solve that?

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
  • You need to explain what you're trying to match. Why are those unexpected? – Barmar Apr 20 '17 at 22:37
  • [don't use `for-in` to loop over arrays](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea?lq=1) – Barmar Apr 20 '17 at 22:38
  • Values used in expression is expected such as "Total = Amx + Hmx + _\n3000" – user3120188 Apr 20 '17 at 22:40
  • `(?!\n)` is a negatitve lookahead. It doesn't do anything if you have it to the left of the pattern, you need to use a negative lookbehind for that. But Javascript doesn't have negative lookbehind. – Barmar Apr 20 '17 at 22:42
  • I think you need to provide some info about the general structure of the string. The way I see it, you want the three first numbers in the string plus the text between the `"`s. Is that correct? – jrook Apr 20 '17 at 23:02
  • why don't you match the numbers with `\d{3,4}` and the comment string with a simple `".+"` ? – jrook Apr 20 '17 at 23:05

0 Answers0