raestro
raestro

Reputation: 35

Regex starting with a string

I want to filter the following string with the regular expressions:

TEST^AB^^HOUSE-1234~STR2255

I wanna get only the string "HOUSE-1234" and I've to test the string always with the beginning "TEST^AB^^" and ending with the "~".

Can you please help me how the regex should look like?

Upvotes: 1

Views: 193

Answers (7)

Ahmed KRAIEM
Ahmed KRAIEM

Reputation: 10427

You should do this without regex:

    var str = "TEST^AB^^HOUSE-1234~STR2255";
    var result = (str.StartsWith("TEST^AB^^") && str.IndexOf('~') > -1) 
                ? new string(str.Skip(9).TakeWhile(c=>c!='~').ToArray())
                : null;
    Console.WriteLine(result);

Upvotes: 0

cat916
cat916

Reputation: 1361

(TEST\^AB\^\^)((\w)+-(\w+))(\~.+)

There are three groups :

(TEST\^AB\^\^) : match yours TEST^AB^^
((\w)+\-(\w+)) : match yours HOUSE-123
(\~.+) : match the rest

Upvotes: 0

Chris Searles
Chris Searles

Reputation: 2412

Don't even need the RegEx for something that well defined. If you want to simplify:

string[] splitString;
if (yourstring.StartsWith("TEST^AB^^"))
{
    yourstring = yourstring.Remove(0, 9);
    splitString = yourstring.Split('~');
    return splitString[0];
}
return null;

Upvotes: 0

I4V
I4V

Reputation: 35353

string input = "TEST^AB^^HOUSE-1234~STR2255";
var matches = Regex.Matches(input, @"TEST\^AB\^\^(.+?)~").Cast<Match>()
                .Select(m => m.Groups[1].Value)
                .ToList();

Upvotes: 1

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98750

You can use \^\^(.*?)\~ pattern which matches start with ^^ and ends with ~

string s = @"TEST^AB^^HOUSE-1234~STR2255";
Match match = Regex.Match(s, @"\^\^(.*?)\~", RegexOptions.IgnoreCase);

if (match.Success)
{
    string key = match.Groups[1].Value;
    Console.WriteLine(key);
}

Output will be;

HOUSE-1234

Here is a DEMO.

Upvotes: 2

Matt Burland
Matt Burland

Reputation: 45135

With the little information you've given us (and assuming that the TEST^AB isn't necessarily constant), this might work:

(?:\^\^).*(?:~)

See here

Or if TEST^AB is constant, you can throw it in too

(?:TEST\^AB\^\^).*(?:~)

The important part is to remember that you need to escape the ^

Upvotes: 0

David
David

Reputation: 16277

string pattern=@"\^\^(.*)\~";
Regex re=new Regex(pattern);

Upvotes: 0

Related Questions