简体   繁体   中英

How to remove First 6 and last 6 characters from a string using regex or c#

I am in need of a transformation script that will remove 1st 6 characters and last 6 characters from a string.

String is as follows: Email reception@oasisdental.com.au Email

I need only reception@oasisdental.com.au

I am scraping data from the internet and I am getting this Email as a prefix as will as suffix, I want to remove both these Email. I have tried regex as well as C# but I am not able to make regex or c# code to do this.

 var s = "your string";
 s = s.Substring(6,s.Length-12);

I think for your requirement, we don't need to care about the number of characters to trim:

Regex reg = new Regex(@"\s.+@.+\s");//This is not a FULL regex for an email address
s = reg.Match(s).Value.Trim();

UPDATE:

string upperLetters = new string(Enumerable.Range(65, 26).Select(c => (char)c).ToArray());
Regex reg = new Regex(string.Format("[(]([{0}]{{2}}.+?)[)]", upperLetters));
s = reg.Match(s).Groups[1].Value;

You can also replace the "Email" string with nothing. However it also remove it from the e-mail name (Ex: bob@email.com)

yourStringName.Replace("Email", string.Empty).TrimStart().TrimEnd();

You can also use Substring , Remove or even a combination of TrimStart and TrimEnd :

string s = s.Substring(6, s.Length - (2 * 6)); //Second parameter is string length, not end index
string s = s.Remove(s.Length - 6, 6).Remove(0, 6);
string s = s.TrimStart("Email ".ToCharArray()).TrimEnd(" Email".ToCharArray());

Honestly, there's really a lot of ways to achieve that.

如果确实必须使用正则表达式,请使用:

/\A.{6}|.{6}\Z/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM