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

Asked

Viewed 605 times

8

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

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

To make it clearer:

"select that word: another word here"

Recalling that the : should not be selected.

  • Try to use this: ^(.*?):

  • @Fernando Has how to do this before the -> (:) ??

  • 3

    Yes, another alternative is to use Match result = Regex.Match(text, @" .*?(?=:)"); in which case regex will take everything down to the first (:)

  • 3

    @Sérgiohenrique You can always choose one (and only one) correct answer to your questions. You mark an answer as correct using the on the left side of the response.

3 answers

14


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

Match result = Regex.Match(text, @"^.*?(?=:)");
  • 3

    Excellent! + 1 easy

  • 2

    Just to add a comment to Fernando’s Regex. This is used .* which corresponds from 0 to unlimited Lazy characters ? and followed by Positive Lookahead (?=alguma_string), that is, it will capture the characters before the string defined in the Lookahead Positive, except line terminators. If you want to include line terminators, use this Regex: [\s\S]*?(?=:)

  • 2

    @danieltakeshi or add the flag s (simple line)

  • 2

    The comment made by @danieltakeshi should be incorporated in the question as explanation of regex. In my opinion all rules should have explanations because it not only adds content to the answer but also helps those who are not in the subject to understand how it works.

11

It is possible to do without regex capturing the character index : and then using the method Substring.

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

  • I will give -1 because it does not address the question using Regex

  • 8

    +1 for showing an alternative to more than the AP requested.

1

There is a concept in regex what call positive lookahead, that is, looking forward to.

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

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

Running on regex101

Browser other questions tagged

You are not signed in. Login or sign up in order to post.