flavour404
flavour404

Reputation: 6312

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

Upvotes: 1

Views: 4094

Answers (2)

trincot
trincot

Reputation: 351308

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 +.

Upvotes: 2

Dominik A. Sztorc
Dominik A. Sztorc

Reputation: 1

Maybe with a use of capture groups?

/(unittime)(\D+)(\d+)(\D+)(,)

The third capturing group (\d+) is your number.

First group matches 'unittime'. Second matches any number of non digits. Third is your number. Fourth is some more non digits. Fifth is the ending coma.

Upvotes: 0

Related Questions