How to give a Regex before a string? And select?

8

What I need to do is this: let's assume the string is - > : .

However, I want to select "only" the string before : using Regex .

To get clearer:

" select this word : another word here"

Remembering that : should not be selected.

    
asked by anonymous 09.01.2018 / 18:44

3 answers

14

In this case REGEX will get everything up to the first one (:)

Match result = Regex.Match(text, @"^.*?(?=:)");
    
09.01.2018 / 18:56
11

You can do without regex by capturing the index of the character : and then using the Substring method.

Example:

var str = "selecionar esta parte:outra coisa aqui";
var i = str.IndexOf(':');

if(i >= 0)
    str = str.Substring(0, i);

Console.WriteLine(str);

See working on .NET Fiddle     

09.01.2018 / 18:56
1

There is a concept in regex that calls positive lookahead , that is, looking ahead.

.*(\w+)(?=:)

Look for a text that has a : in front of the text

Running on regex101

    
23.03.2018 / 16:48