How might I reformulate a "MM/YYYY" date as "YYYYMM"? - c#

I want to convert this string format:
11/2013
TO
201311
So, suppose my string is in this variable:
string s = "11/2013";
What should be the code for this problem? Thanks!

sprime = s.Split(new char [] {'/'});
s = sprime[1] + sprime[0];
This is fastest:
s = s[3] + s[4] + s[5] + s[6] + s[0] + s[1];
If you are converting a gazillion billion records it will matter.

string newString = s.Split('/')[1] + s.Split('/')[0];

string [] split = s.Split('/');
string str = split[1] + split[0];

string s = "11/2011";
s = String.Format("{0}{1}", s.Split('/')[1], s.Split('/')[0]);

Note that this answer assumes s will match, and it will return an empty string if it doesn't.
Using Split will throw an IndexOutOfRangeException when you try to access [1] when there was no /.
You could of course add code to handle these cases regardless of whether you use Regex or Split.
string s = "11/2013";
// Match 1+ digits followed by a forward slash followed by 1+ digits
Regex r = new Regex(#"(\d+)/(\d+)");
var m = r.Match(s);
string result = m.Groups[2].Value + m.Groups[1].Value;

All so complicated. Makes my head hurt. Try this instead:
static readonly Regex rx = new Regex( #"^(\d\d)/(\d\d\d\d)$" ) ;
...
string s1 = "12/3456" ;
string s2 = rx.Replace( s1 , #"$2/$1" ) ;

Or Splitless for [??]/YYYY; s.Substring(s.Length - 4, 4) + s.Substring(0, s.Length - 5);

string s = "11/2013";
Regex r = new Regex("^(?<month>[0-1]?[0-9])/(?<year>[0-9]{4})$");
var match = r.Match(s);
string month = match.Groups["month"].Value;
string year = match.Groups["year"].Value;
string result = year + month;

Related

Trim a string in c# after special character

I want to trim a string after a special character..
Lets say the string is str="arjunmenon.uking". I want to get the characters after the . and ignore the rest. I.e the resultant string must be restr="uking".
How about:
string foo = str.EverythingAfter('.');
using:
public static string EverythingAfter(this string value, char c)
{
if(string.IsNullOrEmpty(value)) return value;
int idx = value.IndexOf(c);
return idx < 0 ? "" : value.Substring(idx + 1);
}
you can use like
string input = "arjunmenon.uking";
int index = input.LastIndexOf(".");
input = input.Substring(index+1, input.Split('.')[1].ToString().Length );
Use Split function
Try this
string[] restr = str.Split('.');
//restr[0] contains arjunmenon
//restr[1] contains uking
char special = '.';
var restr = str.Substring(str.IndexOf(special) + 1).Trim();
Try Regular Expression Language
using System.IO;
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "arjunmenon.uking";
string pattern = #"[a-zA-Z0-9].*\.([a-zA-Z0-9].*)";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine(match.Value);
if (match.Groups.Count > 1)
for (int ctr = 1; ctr < match.Groups.Count; ctr++)
Console.WriteLine(" Group {0}: {1}", ctr, match.Groups[ctr].Value);
}
}
}
Result:
arjunmenon.uking
Group 1: uking
Personally, I won't do the split and go for the index[1] in the resulting array, if you already know that your correct stuff is in index[1] in the splitted string, then why don't you just declare a constant with the value you wanted to "extract"?
After you make a Split, just get the last item in the array.
string separator = ".";
string text = "my.string.is.evil";
string[] parts = text.Split(separator);
string restr = parts[parts.length - 1];
The variable restr will be = "evil"
string str = "arjunmenon.uking";
string[] splitStr = str.Split('.');
string restr = splitStr[1];
Not like the methods that uses indexes, this one will allow you not to use the empty string verifications, and the presence of your special caracter, and will not raise exceptions when having empty strings or string that doesn't contain the special caracter:
string str = "arjunmenon.uking";
string restr = str.Split('.').Last();
You may find all the info you need here : http://msdn.microsoft.com/fr-fr/library/b873y76a(v=vs.110).aspx
cheers
I think the simplest way will be this:
string restr, str = "arjunmenon.uking";
restr = str.Substring(str.LastIndexOf('.') + 1);

Regex return bad string

in string "<-6838.36,-6723.11,0,0> <-7091.07,-6554.64,133,0> <-368,-368,0,1> <-400,-432,0,1> <-336,-432,0,1> <-304,-368,0,1> "
pattern1 #"\<(.*?),(.*?),(.*?),0\>";
pattern2 #"\<(.*?),(.*?),(.*?),1\>";
result 1:"-6838.36" 2:"-6723.11" 3:"0,0> <-7091.07,-6554.64,133,0> <-368,-368,0"
need: 1:"-6838.36" 2:"-6723.11" 3:"0"
code:
string instring = "<-6838.36,-6723.11,0,0> <-7091.07,-6554.64,133,0> <-368,-368,0,1> <-400,-432,0,1> <-336,-432,0,1> <-304,-368,0,1> ";
string myteamheroes = #"\<(.*?),(.*?),(.*?),0\>";
string enemyheroes = #"\<(.*?),(.*?),(.*?),1\>";
MatchCollection collmytmheros = Regex.Matches(instring, myteamheroes);
MatchCollection collenemytmheros = Regex.Matches(instring, enemyheroes);
var us_EN = new CultureInfo("en-US");
foreach (Match herodata in collmytmheros)
{
String sX = herodata.Groups[1].Value;
String sY = herodata.Groups[2].Value;
String sR = herodata.Groups[3].Value;
double fX = float.Parse(sX, us_EN) + 7250.0d;
double fY = float.Parse(sY, us_EN) + 7950.0d;
int fR = int.Parse(sR);
// here error
//...other code
}
foreach (Match herodata in collenemytmheros)
{
String sX = herodata.Groups[1].Value;
String sY = herodata.Groups[2].Value;
String sR = herodata.Groups[3].Value;
// MessageBox.Show("1:\"" + sX +"\"2:\"" + sY + "?" + "\"3:\"" + "?");
double fX = float.Parse(sX, us_EN) + 7250.0d;
double fY = float.Parse(sY, us_EN) + 7950.0d;
int fR = int.Parse(sR);
// here error
//... other code
}
Did I wrote anything wrong?
Could try the following regular expressions to match the results:
Pattern 1
\<([-0-9.]+),([-0-9.]+),([-0-9.]+),0\>
Patter 2
\<([-0-9.]+),([-0-9.]+),([-0-9.]+),1\>
I'm not entirely sure I understand what you're doing, so a regex might not be the best way to go about parsing your data. That said, I think the problem you're having is that the (.*?),0\> section will run past the end of your small groups of <data>, and run into the next set to obtain a match.
If you're sure there are only going to be numbers in there, you can alter your regex to be more specific:
e.g <([\d-.]+),([\d-.]+),([\d-.]+),0> (with a 1 instead of the 0 for your 'enemies').

Format string with regex in c#

I would like to format a string that looks like this
BPT4SH9R0XJ6
Into something that looks like this
BPT4-SH9R-0XJ6
The string will always be a mix of 12 letters and numbers
Any advice will be highly appreciated, thanks
Try Regex.Replace(input, #"(\w{4})(\w{4})(\w{4})", #"$1-$2-$3");
Regex is often derided, but is a pretty neat way of doing what you need. Can be extended to more complex requirements that are difficult to meet using string methods.
You can use "(.{4})(.{4})(.{4})" as your expression and "$1-$2-$3" as your replacement. This is, however, hardly a good use for regexp: you can do it much easier with Substring.
var res = s.Substring(0,4)+"-"+s.Substring(4,4)+"-"+s.Substring(8);
If the rule is to always split in three block of four characters no need for a reg exp:
str.Substring(0,4) + "-" + str.Substring(4,4) + "-" + str.Substring(8,4)
It would seem that a combination of String.Concat and string.Substring should take care of everything that you need.
var str = "BPT4SH9R0XJ6";
var newStr = str.Substring(0, 4) + "-" + str.Substring(4, 4) + "-" + str.Substring(8, 4);
Any reason you want to do a regex? you could just insert hyphens:
string s = "BPT4SH9R0XJ6";
for(int i = 4; i < s.length; i = i+5)
s = s.Insert(i, "-");
This would keep adding hyphens every 4 characters, would not error out if string was too short/long/etc.
return original_string.SubString(0,4)+"-"+original_string.SubString(4,4)+"-"+original_string.SubString(8,4);
string str = #"BPT4SH9R0XJ6";
string formattedString = string.Format("{0}-{1}-{2}", str.Substring(0, 4), str.Substring(4,4), str.Substring(8,4));
This works with any length of string:
for (int i = 0; i < (int)Math.Floor((myString.Length - 1) / 4d); i++)
{
myString = myString.Insert((i + 1) * 4 + i, "-");
}
Ended upp using this
var original = "BPT4SH9R0XJ6".ToCharArray();
var first = new string(original, 0, 4);
var second = new string(original, 4, 4);
var third = new string(original, 8, 4);
var mystring = string.Concat(first, "-", second, "-", third);
Thanks
If you are guaranteed the text you're operating on is the 12 character code then why don't you just use substring? Why do you need the Regex?
String theString = "AB12CD34EF56";
String theNewString = theString.Substring(0, 4) + "-" + theString.Substring(4, 4) + "-" + theString.Substring(8, 4);'

strip out digits or letters at the most right of a string

I have a file name: kjrjh20111103-BATCH2242_20111113-091337.txt
I only need 091337, not the txt or the - how can I achieve that. It does not have to be 6 numbers it could be more or less but will always be after "-" and the last ones before ."doc" or ."txt"
You can either do this with a regex, or with simple string operations. For the latter:
int lastDash = text.LastIndexOf('-');
string afterDash = text.Substring(lastDash + 1);
int dot = afterDash.IndexOf('.');
string data = dot == -1 ? afterDash : afterDash.Substring(0, dot);
Personally I find this easier to understand and verify than a regular expression, but your mileage may vary.
String fileName = kjrjh20111103-BATCH2242_20111113-091337.txt;
String[] splitString = fileName.Split ( new char[] { '-', '.' } );
String Number = splitString[2];
Regex: .*-(?<num>[0-9]*). should do the job. num capture group contains your string.
The Regex would be:
string fileName = "kjrjh20111103-BATCH2242_20111113-091337.txt";
string fileMatch = Regex.Match(fileName, "(?<=-)\d+", RegexOptions.IgnoreCase).Value;
String fileName = "kjrjh20111103-BATCH2242_20111113-091337.txt";
var startIndex = fileName.LastIndexOf('-') + 1;
var length = fileName.LastIndexOf('.') - startIndex;
var output = fileName.Substring(startIndex, length);

C# split string on X number of alpha numeric values

this might be simple question I have 3 strings
A123949DADWE2ASDASDW
ASDRWE234DS2334234234
ZXC234ASD43D33SDF23SDF
I want to split those by the first 8 characters and then the 10th and 11th and then combine them into one string.
So I would get:
A123949DWE
ASDRWE23S2
ZXC234AS3D
Basically the 9th character and anything after the 12th character is removed.
You can use String.Substring:
s = s.Substring(0, 8) + s[10] + s[11]
Example code:
string[] a = {
"A123949DADWE2ASDASDW",
"ASDRWE234DS2334234234",
"ZXC234ASD43D33SDF23SDF"
};
a = a.Select(s => s.Substring(0, 8) + s[10] + s[11]).ToArray();
Result:
A123949DWE
ASDRWE23S2
ZXC234AS3D
So let's say you have them declared as string variables:
string s1 = "A123949DADWE2ASDASDW";
string s2 = "ASDRWE234DS2334234234";
string s3 = "ZXC234ASD43D33SDF23SDF";
You can use the substring to get what you want:
string s1substring = s1.Substring(0,8) + s1.Substring(9,2);
string s2substring = s1.Substring(0,8) + s1.Substring(9,2);
string s3substring = s1.Substring(0,8) + s1.Substring(9,2);
And that should give you what you need. Just remember, that the string position is zero-based so you'll have to subtract one from the starting position.
So you could do:
string final1 = GetMyString("A123949DADWE2ASDASDW");
string final2 = GetMyString("ASDRWE234DS2334234234");
string final3 = GetMyString("ZXC234ASD43D33SDF23SDF");
public function GetMyString(string Original)
{
string result = Original.Substring(12);
result = result.Remove(9, 1);
return result;
}

Categories

Resources