Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select three characters unless they follow an @ sign for the TextBuffer .replace()

I want to select and replace three characters, say "STR", unless they are after an @ sign.

I use the text buffer class with the replace method. I am able to replace the three characters, but it also replaces the character before the three characters.

This is my code:

static void simpleReplace(Args _args)
{
    TextBuffer txtb = new TextBuffer();         

    txtb.setText(" STR @STR #STR");
    txtb.regularExpressions(true);

    txtb.replace("[^@]STR", "FOO");
    info(txtb.getText());        
}

The result is "FOO @STR FOO".

The result I want is " FOO @STR #FOO", with the space and # intact.

I think the problem is that that I am matching four characters but only want to replace three. I assume I need a non-capturing group or some lookaround. I have tried the following expression in Debuggex:

[^@](?:(STR))

Regular expression visualization

Debuggex Demo

This seems to work and selects the three characters if they do not follow an @, but does not seem to be supported by Dynamics AX. I looked at this page for X++ RegEx support, but couldn't find any syntax that will solve my problem.

Is it possible to change the job above to result in this output: " FOO @STR #FOO".

like image 841
Tina van der Vyver Avatar asked Nov 16 '25 08:11

Tina van der Vyver


1 Answers

I am having a hard time thinking of a single replace solution with the limited syntax of regular expressions allowed. I have a solution but it's not optimal and may not work in your specific situation.

static void simpleReplace(Args _args)
{
    TextBuffer txtb = new TextBuffer();         

    txtb.setText(" STR @STR #STR");
    txtb.regularExpressions(true);

    txtb.replace("STR", "FOO");
    txtb.replace("@FOO", "@STR");
    info(txtb.getText());        
}

Replace all STR with FOO then all @FOO with @STR. It should have the same effect, however this may not be ideal for you depending on the data.

like image 143
d0nut Avatar answered Nov 18 '25 22:11

d0nut