Page 1 of 1

RegEx replace in Script expression

Posted: Sat Apr 20, 2019 4:14 pm
by hover27
Hi,

I'm new with scripting in Switch.<br/>

I would like to replace RegEx Strings by group.
For example a string like 'a1b2c3_DDYYKK_123_ABC_X1Y1Z1'
The replaced string should be the substring between the 2nd and 3rd underscore -> '123'

If I use replace, that does not work.
Does anyone have an idea, why?

Code: Select all

var name = job.getJobState();
var pattern = /(.{0,9}_.{0,9}_)(.{1,9})(_.{1,9}_.{1,9})/;		   
var newname = name.replace(pattern,$2);

newname;

thank you

Re: RegEx replace in Script expression

Posted: Sun Apr 21, 2019 1:00 am
by hover27
I answer myself:
look here:
http://www.enfocus.com/manuals/Develope ... egexp.html

.replace doesn't work in Switch Javascript.

The solution looks like this:

Code: Select all

    re = /name: ([a-zA-Z ]+)/; 
    re.search( "name: John Doe, age: 42" ); 
    re.cap(0);  // returns "name: John Doe" 
    re.cap(1);  // returns "John Doe" 
    re.cap(2);  // returns undefined, no more captures.

Re: RegEx replace in Script expression

Posted: Mon Apr 22, 2019 10:00 am
by Padawan
Replace does work in Switch javascript, it is a method in the string class :
https://www.enfocus.com/manuals/Develop ... ring.html

I can't try myself now but I think your first script will work when you replace

Code: Select all

var newname = name.replace(pattern,$2);
With

Code: Select all

var newname = name.replace(pattern,"\\2" );

Re: RegEx replace in Script expression

Posted: Tue Apr 23, 2019 5:11 pm
by cstevens
you can also use the String.split('_') and Array.join('_') methods to convert these strings into an array and then modify the 3rd instance of the array:

Code: Select all

	var inString = "a1b2c3_DDYYKK_123_ABC_X1Y1Z1";
	var strArray = inString.split('_');
	strArray[2] = "456";
	inString = strArray.join("_");
	s.log(1, "Modified String is: " + inString);

Re: RegEx replace in Script expression

Posted: Wed Apr 24, 2019 11:29 am
by hover27
Thank you, both works :-)