flavour404 flavour404 -4 years ago 133
Javascript Question

regular expression, match any number after string

My string looks like this:

\r\n\r\n\t\"unittime\":\"2017010100\", \r\n\t\"count"\r


Using a regex I want to match on any number that follows the word 'unittime' and before the '",' at the end, how do I do that?

So for the above string I would end up with

result = 2017010100

Answer Source

You could use this regular expression:

unittime[^,]*?(\d+)

var s = '\r\n\r\n\t\"unittime\":\"2017010100\", \r\n\t\"count"\r ';
var num = +(s.match(/unittime[^,]*?(\d+)/) || [])[1];

console.log(num);

Explanation

  • [^,] matches any character that is not a comma
  • *? repeats the previous pattern as few times as possible (= lazy, not greedy) in order to match the complete regular expression
  • ( ): creates a capture group, which can later be referenced
  • \d: matches a digit
  • +: matches the previous pattern one or more times (greedy)

s.match returns an array with first the complete match (unittime\":\"2017010100), and in the next elements the values for the capture groups: we only have one such group, so at index 1 we'll get 2017010100.

If there is no match, then .match() will return null. In that case the || will kick in and create an empty array instead. Either way, the result is an array. With [1] the capture group match is taken. Of course, [] does not have such an element, so in that case you get undefined.

Finally, this result (a string or undefined) is converted to a number with the unitary +.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download