Alan2
Alan2

Reputation: 24602

How can I eliminate a quote from the start of my string using regex?

I have strings that sometimes start like this:

"[1][v5r,vi][uk]

Other times like this:

[1][v5r,vi][uk]

How can I remove the " when it appears at the start of a string using Regex? I know I need to do something like this, but not sure how to set it up:

regex = new Regex(@"(\n  )?\[ant=[^\]]*\]");
regex.Replace(item.JmdictMeaning, ""));

Upvotes: 1

Views: 74

Answers (5)

Sushant Yelpale
Sushant Yelpale

Reputation: 889

string.StartsWith will do the trick

string str = "\"[1][v5r,vi][uk]";
if(str.StartsWith('"'))
    str = str.Substring(1);

Upvotes: 1

Impostor
Impostor

Reputation: 2050

use TrimStart() to remove this character if exists

string str = "\"a[1][v5r,vi][uk]";
str= str.TrimStart('\"');

Upvotes: 0

Suhas Parameshwara
Suhas Parameshwara

Reputation: 1454

It can be done using indexOf and Substring

string str = "\"a[1][v5r,vi][uk]";
Console.WriteLine(str.Substring(str.IndexOf('[')));

Upvotes: 0

Matthew Watson
Matthew Watson

Reputation: 109852

If the string always starts with [1]:

int indexOfFirstElement = item.IndexOf("[1]");

if (indexOfFirstElement > 0)
    item = item.Substring(indexOfFirstElement);

If you just want to start at the first [:

int indexOfFirstElement = item.IndexOf('[');

if (indexOfFirstElement > 0)
    item = item.Substring(indexOfFirstElement);

Simpler than Regex, which is probably overkill for this problem.

Upvotes: 4

HariHaran
HariHaran

Reputation: 4199

Here you go

string input =@" ""[1][v5r,vi][uk]";
string pattern = @"^\s*""?|""?\s*$";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, "");
Console.WriteLine(result);

You can find my Example here in dotnetfiddle

Upvotes: 1

Related Questions