RegEx replace in Script expression

Post Reply
hover27
Newbie
Posts: 14
Joined: Sat Apr 20, 2019 3:49 pm

RegEx replace in Script expression

Post 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
hover27
Newbie
Posts: 14
Joined: Sat Apr 20, 2019 3:49 pm

Re: RegEx replace in Script expression

Post 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.
Padawan
Advanced member
Posts: 358
Joined: Mon Jun 12, 2017 8:48 pm
Location: Belgium
Contact:

Re: RegEx replace in Script expression

Post 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" );
cstevens
Member
Posts: 103
Joined: Tue Feb 12, 2013 8:42 pm

Re: RegEx replace in Script expression

Post 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);
hover27
Newbie
Posts: 14
Joined: Sat Apr 20, 2019 3:49 pm

Re: RegEx replace in Script expression

Post by hover27 »

Thank you, both works :-)
Post Reply