3

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".

  • Do you know if X++ supports look behind? if so then try this: `(?<!@)STR` – d0nut Dec 30 '15 at 17:49
  • https://regex101.com/r/mK5vY6/1 for an example of the above regex – d0nut Dec 30 '15 at 17:50
  • If X++ doesn't support lookbehind then try this: `([^@])STR` and change the replace string to `$1FOO` (it may be `\1FOO` depending on syntax) – d0nut Dec 30 '15 at 17:53
  • Thanks for all the options! Unfortunately, none of them work. I also thought it would be based on C#, but I guess since the TextBuffer class has been around since Dynamics' Axapta days, it's X++ based. – Tina van der Vyver Dec 30 '15 at 18:17
  • Came up with a new answer. It's the best answer I could come up with, with the limited syntax. – d0nut Dec 30 '15 at 18:36

1 Answers1

5

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.

d0nut
  • 2,835
  • 1
  • 18
  • 23
  • While not a pretty solution I agree that this is probably the quickest way to solve this problem. In my data I have "@STR" that needs to stay "@STR", but based on your suggestion I can replace the text in three steps. Thanks! – Tina van der Vyver Jan 04 '16 at 10:25
  • @TinavanderVyver no problem! it's the best thing I could think of :/ – d0nut Jan 04 '16 at 11:18