SmartestVEGA
SmartestVEGA

Reputation: 8889

Regex clarification

I have the following java-script to extract a word which occur after an "=" in a string.

For example:

string strOld="ActionDate=11/20/2014 12:00:00 AM ";

strOld.substr(strOld.indexOf(type)).substr(type.length +1, strOld.substr(strOld.indexOf(type)).substr(type.length).indexOf(" "))

This will extract "11/20/2014" from the above string.Since this is the word which is occuring after "=".

How can we rewrite using Regex?

I want to get comma separated dates in case of re-occurrence of the "=" in the same string variable.

In case of multiple signs :

Input : string strOld="ActionDate=11/20/2014 12:00:00 AM SuspensionCode=123"; Output : "11/20/2014,123"

Upvotes: 1

Views: 67

Answers (3)

Mottie
Mottie

Reputation: 86413

If you don't care about the word to the left of the equal, then you can use this regex to split it:

'ActionDate=11/20/2014 12:00:00 AM SuspensionCode=123'.split(/\w+=/);
// result: ["", "11/20/2014 12:00:00 AM ", "123"]

or if you want to include them in the array, try this:

'ActionDate=11/20/2014 12:00:00 AM SuspensionCode=123'.split(/(\b\w+)=/)
// result ["", "ActionDate", "11/20/2014 12:00:00 AM ", "SuspensionCode", "123"]

Upvotes: 1

Bogie
Bogie

Reputation: 153

First split the string into array, then extract the date from the second item in the array, which is the datetime string.

var strOld = "ActionDate=11/20/2014 12:00:00 AM";
var arr = strOld.split('=');
var regex = /([\d]{2}\/[\d]{2}\/[\d]{4})\s([\d]{2}:[\d]{2}:[\d]{2}\s(AM|PM))/;
var result;
arr[1].replace(regex, function(date, time) {
    result = date;
    console.log(result);
});

Upvotes: 1

buckley
buckley

Reputation: 14069

This is a javascript version

https://fiddle.jshell.net/nsqbuy11/1/

Just got to know jshell and seems a nice tool

var myregexp = /=(\S*)/g;
var match = myregexp.exec("FirstEvictionActionDate=11/20/2014 12:00:00 AM SuspensionCode=123");
while (match != null) {
  //for (var i = 0; i < match.length; i++) {
    alert((match[1]));
  //}
  match = myregexp.exec("FirstEvictionActionDate=11/20/2014 12:00:00 AM SuspensionCode=123");
}

Upvotes: 3

Related Questions