Skip to main content
Known Participant
December 11, 2024
Answered

How to replace string while creating variable using GREP search pattern

  • December 11, 2024
  • 2 replies
  • 1051 views

// constraints are:

// XX T will always be first and in caps ==> ^XX T

// T will always have a value of max of 2 digits ==> {1,2}

// L may or may not be present but if present will always have a value of max of 2 digits ==> {1,2}

// the digits of L if present will always be the end of the string ==> (/\d+$/)

 

var testName1 = "XX T3 L22";  // viable upper case search(/^XX T\d{1,2}( L\d{1,2}$)/g)

var testName2 = "XX T44 L1";

 

var testName3 = "XX T5";  // viable upper case search(/^XX T\d{1,2}$/g)

var testName4 = "XX T66;

 

 

// for testName1 ==> lNumber1 = 22

if (testName1.toString().search(/^XX T\d{1,2}( L\d{1,2}$)/g) === 0) lNumber1 = testName1.toString().replace((/^XX T\d{1,2}( L\d{1,2}$)/g), testName1.toString().match(/\d+$/));
 
// how can I return the T value in all 4 examples?
// results:
// lNumber1 = 3
// lNumber2 = 44
// lNumber3 = 5
// lNumber4 = 66
This topic has been closed for replies.
Correct answer m1b

Hi @nutradial, I assume you are doing this via ExtendScript... see if this helps. The match method of string is great for this.

- Mark

 

var tests = [
    "XX T3 L22",
    "XX T44 L1",
    "XX T5",
    "XX T66"
];

// match two digits of T and two digits of L (if L exists)
var matcher = /^XX T(\d{1,2})(?: L(\d{1,2}))?/;

for (var i = 0, T, L; i < tests.length; i++) {

    // perform the regex match
    var match = tests[i].match(matcher);

    if (!match)
        // no match at all
        continue;

    T = match.length > 0 ? Number(match[1]) : undefined;
    L = match.length > 1 ? Number(match[2]) : undefined;

    $.writeln('test string "' + tests[i] + '":  T = ' + T + '  L = ' + L);

}

 

2 replies

m1b
Community Expert
m1bCommunity ExpertCorrect answer
Community Expert
December 11, 2024

Hi @nutradial, I assume you are doing this via ExtendScript... see if this helps. The match method of string is great for this.

- Mark

 

var tests = [
    "XX T3 L22",
    "XX T44 L1",
    "XX T5",
    "XX T66"
];

// match two digits of T and two digits of L (if L exists)
var matcher = /^XX T(\d{1,2})(?: L(\d{1,2}))?/;

for (var i = 0, T, L; i < tests.length; i++) {

    // perform the regex match
    var match = tests[i].match(matcher);

    if (!match)
        // no match at all
        continue;

    T = match.length > 0 ? Number(match[1]) : undefined;
    L = match.length > 1 ? Number(match[2]) : undefined;

    $.writeln('test string "' + tests[i] + '":  T = ' + T + '  L = ' + L);

}

 

nutradialAuthor
Known Participant
December 11, 2024

Nice!!! Thanks. 

m1b
Community Expert
Community Expert
December 11, 2024

You're welcome!

nutradialAuthor
Known Participant
December 11, 2024