Kevin
Kevin

Reputation: 1614

Find first occurrence of pattern in regex

If I am looking through text like this:

hello bob hello hello hello

I want to find the first instance of hello and take it out, so I use a pattern like this

hello

When I erase that pattern, this is what the text is

bob

but what I need is

bob hello hello hello

How do I modify it to only find the first occurrence of the pattern

Upvotes: 1

Views: 2131

Answers (2)

Miguel Ventura
Miguel Ventura

Reputation: 10468

In OutSystems, regex functions are provided through extensions, so I'll assume that you are using the Text extension. The extension code maps to .NET / Java code and the underlying calls to the regex methods are Replace(string input, string replacement) for .NET and replaceAll(String replacement) for Java. These will both replace all occurrences of your regexp on the given input string.

Now, several ways into solving your problem...

If you want to replace in the beginning of the string: In the example you've given, the hello you're interested in removing is also in the beginning of the input string. In that particular case you could use a regular expression such as ^hello.

If you want to replace the first match, anywhere in the string: If you're interested in replacing the first occurrence but that can be anywhere in the input string, then you could write an expression such as hello(.*) and use as replacement string $1. In this case, $1 would mean the capturing group (.*) which would include all further occurrences of hello. This works both for .NET and Java. Of course this way of doing things is neither pretty nor efficient so...

If you want to have more regex capabilities: you can use Integration Studio to download and open the Text extension and add any new methods that you want, although since this extension is included in the platform and can be replaced by an upgrade, I'd suggest creating your own extension and using the Text extension as a template. You could create an extension action very similar to the current Replace one but that could take an additional count parameter or something similar.

Upvotes: 1

guessimtoolate
guessimtoolate

Reputation: 8642

My crystal bowl tells me you're using some sort of a global modifier in your regexp and if you leave it out then you should get the result you expect. For example in javascript you would use:

/hello/

instead of:

/hello/g

Upvotes: 2

Related Questions