Penguen
Penguen

Reputation: 17278

How to drop some characters with Regex in vs?

I have a sql table and I have a column which includes data such as: B757-34-11-00-I-1, A300-223100-0503-1 etc.

A300-223100-0503-1 -> 223100-0503-1
B757-34-11-00-I-1 -> 34-11-00-I-1

How can i do that with regex? I need two kinds of solutions: sql and C#. how can I do that with sql query in SQL and C#

i need drop charater as far as "-" may be dropping more than 5 characters or less than? i need also drop "-"

Upvotes: 0

Views: 244

Answers (4)

Frank
Frank

Reputation: 2648

In SQL:

SUBSTRING(col, PATINDEX('%-%', col) + 1)

in C#:

val.Substring(val.IndexOf('-') + 1)

This requirement is so simple, there is no need for regexes (and SQL Server does not natively support them anyway if you do not add this via a stored procedure implemented in .net).

Upvotes: 0

Guffa
Guffa

Reputation: 700302

A regular expression is overkill for simple string manipulation like this.

C#:

value.Substring(value.indexOf('-') + 1)

SQL:

substring(field, charindex('-', field) + 1, 1000)

(The last parameter could be calculated as len(field) - charindex('-', field) - 1, but you can just use a value that you know is larger than the max length.)

Upvotes: 2

Amarghosh
Amarghosh

Reputation: 59451

string input = "A300-223100-0503-1";
Regex rgx = new Regex("^[^-]+-(.*)$");
string result = rgx.Replace(input, "$1");
Console.WriteLine(result);

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500375

Is it always just dropping the first 5 characters? If so, you don't need to use a regex at all.

C#:

value = value.Substring(5);

T-SQL:

SELECT SUBSTRING(field, 5, LEN(field) - 5)

Upvotes: 1

Related Questions