C sharp delimiter - c#-3.0

In a given sentence i want to split into 10 character string. The last word should not be incomplete in the string. Splitting should be done based on space or , or .
For example:
this is ram.he works at mcity.
now the substring of 10 chars is,
this is ra.
but the output should be,
this is.
Last word should not be incomplete

You can use a regular expression that checks that the character after the match is not a word character:
string input = "this is ram.he";
Match match = Regex.Match(input, #"^.{0,10}(?!\w)");
string result;
if (match.Success)
{
result = match.Value;
}
else
{
result = string.Empty;
}
Result:
this is
An alternative approach is to build the string up token by token until adding another token would exceed the character limit:
StringBuilder sb = new StringBuilder();
foreach (Match match in Regex.Matches(input, #"\w+|\W+"))
{
if (sb.Length + match.Value.Length > 10) { break; }
sb.Append(match.Value);
}
string result = sb.ToString();

Not sure if this is the sort of thing you were looking for. Note that this could be done a lot cleaner, but should get you started ... (may want to use StringBuilder instead of String).
char[] delimiterChars = { ',', '.',' ' };
string s = "this is ram.he works at mcity.";
string step1 = s.Substring(0, 10); // Get first 10 chars
string[] step2a = step1.Split(delimiterChars); // Get words
string[] step2b = s.Split(delimiterChars); // Get words
string sFinal = "";
for (int i = 0; i < step2a.Count()-1; i++) // copy count-1 words
{
if (i == 0)
{
sFinal = step2a[i];
}
else
{
sFinal = sFinal + " " + step2a[i];
}
}
// Check if last word is a complete word.
if (step2a[step2a.Count() - 1] == step2b[step2a.Count() - 1])
{
sFinal = sFinal + " " + step2b[step2a.Count() - 1] + ".";
}
else
{
sFinal = sFinal + ".";
}

Related

Aspose Worksheet not parsing decimal numbers correctly on German server; ignoring period delimiter (123.45 -> 12345)

I have an import task that parses a huge .dat file as an Aspose Workbook.
This was the original code:
public static List<QueryResult> GetAsposeExcelDocumentWithSheetIndex(string filename, string propertyNames, int sheetIndex = 0, int skipRows = 0, int columnToScanForValidEntries = 0, Stream stream = null)
{
Sitecore.Diagnostics.Log.Info("Begin GetAsposeExcelDocumentWithSheetIndex: Filename: " + filename, typeof(UploadHelper));
var loadOptions = new Aspose.Cells.LoadOptions(LoadFormat.Excel97To2003);
if (filename.EndsWith(".xlsx"))
{
loadOptions = new Aspose.Cells.LoadOptions(LoadFormat.Xlsx);
}
else if (filename.EndsWith(".dat") || filename.EndsWith(".csv"))
{
loadOptions = new Aspose.Cells.LoadOptions(LoadFormat.CSV);
}
//var fsStats = new StreamWriter(HttpContext.Current.Server.MapPath("/_uploads/ftp/import.txt"), false);
//fsStats.WriteLine(DateTime.Now.ToString("h:mm:ss") + " - Opening file: " + filename);
//fsStats.Flush();
loadOptions.ParsingFormulaOnOpen = false;
try
{
var workbook = stream != null ? new Workbook(stream: stream, loadOptions: loadOptions) : new Aspose.Cells.Workbook(filename, loadOptions);
Worksheet worksheet = workbook.Worksheets[sheetIndex];
//fsStats.WriteLine(DateTime.Now.ToString("h:mm:ss") + " - Opened sheet");
//fsStats.Flush();
var list = new List<QueryResult>();
for (int i = skipRows, loopTo = worksheet.Cells.Rows.Count + skipRows - 1; i <= loopTo; i++)
{
//fsStats.WriteLine(DateTime.Now.ToString("h:mm:ss") + " - Reading row: " + i);
//fsStats.Flush();
if (worksheet.Cells.GetCell(i, columnToScanForValidEntries) != null &&
worksheet.Cells.GetCell(i, columnToScanForValidEntries).Value != null)
{
NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
var obj = new QueryResult();
var propNames = propertyNames.Split(',');
for (int j = 0, loopTo1 = propNames.Length - 1; j <= loopTo1; j++)
{
Cell cellInfo = worksheet.Cells.GetCell(i, j);
if (cellInfo != null)
{
// specific excluded properties
var propName = propNames[j];
var parseAsString = PropNameShouldNeverBeParsedAsDate(propName);
if ((cellInfo.Type == CellValueType.IsDateTime) && !parseAsString && cellInfo.DateTimeValue.Year > 2010 && !cellInfo.Name.StartsWith("X") && !cellInfo.Name.StartsWith("Y") && !cellInfo.Name.StartsWith("AC")) // this second check is bc some dates weren't return as a DateTime type in the Iplot file
{
// Colmun X and Y should NEVER be a date time
obj.Properties.Add(propNames[j], cellInfo.DateTimeValue);
}
else
{
obj.Properties.Add(propNames[j], cellInfo.StringValue);
}
}
else
{
obj.Properties.Add(propNames[j], null);
}
}
list.Add(obj);
}
}
//fsStats.WriteLine(DateTime.Now.ToString("h:mm:ss") + " - Done reading");
//fsStats.Flush();
//fsStats.Close();
return list;
}
catch (Exception ex)
{
Sitecore.Diagnostics.Error.LogError("Error GetAsposeExcelDocumentWithSheetIndex:" + ex.ToString() + ex.StackTrace);
//fsStats.WriteLine(DateTime.Now.ToString("h:mm:ss") + " - Error: " + ex.ToString());
//fsStats.Flush();
//fsStats.Close();
}
return null;
}
This worked as expected on my local, however the production website is hosted in Germany. The code runs correctly when manually triggered from the admin page (which requires being logged into Sitecore), but when run automatically as a scheduled task, it fails because it's not parsing numbers correctly
public static List<QueryResult> GetAsposeExcelDocumentWithSheetIndex(string filename, string propertyNames, int sheetIndex = 0, int skipRows = 0, int columnToScanForValidEntries = 0, Stream stream = null)
{
//var fsStats = new StreamWriter(HttpContext.Current.Server.MapPath("/_uploads/ftp/import.txt"), false);
//fsStats.WriteLine(DateTime.Now.ToString("h:mm:ss") + " - Opening file: " + filename);
//fsStats.Flush();
loadOptions.ParsingFormulaOnOpen = false;
try
{
var workbook = stream != null ? new Workbook(stream: stream, loadOptions: loadOptions) : new Aspose.Cells.Workbook(filename, loadOptions);
Worksheet worksheet = workbook.Worksheets[sheetIndex];
//fsStats.WriteLine(DateTime.Now.ToString("h:mm:ss") + " - Opened sheet");
//fsStats.Flush();
var list = new List<QueryResult>();
for (int i = skipRows, loopTo = worksheet.Cells.Rows.Count + skipRows - 1; i <= loopTo; i++)
{
//fsStats.WriteLine(DateTime.Now.ToString("h:mm:ss") + " - Reading row: " + i);
//fsStats.Flush();
if (worksheet.Cells.GetCell(i, columnToScanForValidEntries) != null &&
worksheet.Cells.GetCell(i, columnToScanForValidEntries).Value != null)
{
NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
var obj = new QueryResult();
var propNames = propertyNames.Split(',');
for (int j = 0, loopTo1 = propNames.Length - 1; j <= loopTo1; j++)
{
Cell cellInfo = worksheet.Cells.GetCell(i, j);
if (cellInfo != null)
{
// specific excluded properties
var propName = propNames[j];
var parseAsString = PropNameShouldNeverBeParsedAsDate(propName);
if ((cellInfo.Type == CellValueType.IsDateTime) && !parseAsString && cellInfo.DateTimeValue.Year > 2010 && !cellInfo.Name.StartsWith("X") && !cellInfo.Name.StartsWith("Y") && !cellInfo.Name.StartsWith("AC")) // this second check is bc some dates weren't return as a DateTime type in the Iplot file
{
// Colmun X and Y should NEVER be a date time
obj.Properties.Add(propNames[j], cellInfo.DateTimeValue);
}
else
{
var value = cellInfo.StringValue;
if (cellInfo.Type == CellValueType.IsNumeric || propName.Contains("NUM_VALUE"))
{
try
{
if (cellInfo.StringValue == "2.074.927" || cellInfo.DoubleValue == 2074927 || cellInfo.DoubleValue == 2074.927)
{
Sitecore.Diagnostics.Log.Info("Value: " + cellInfo.Value.ToString() + " StringValue: " + cellInfo.StringValue + " DoubleValue: " + cellInfo.DoubleValue.ToString(nfi), typeof(UploadHelper));
Sitecore.Diagnostics.Log.Info("Convert.ToDouble Value: " + Convert.ToDouble(cellInfo.Value) + ", " + Convert.ToDouble(cellInfo.Value).ToString(nfi), typeof(UploadHelper));
Sitecore.Diagnostics.Log.Info("DoubleValue: " + (cellInfo.DoubleValue) + ", " + (cellInfo.DoubleValue).ToString(nfi), typeof(UploadHelper));
Sitecore.Diagnostics.Log.Info("StringValue: " + (cellInfo.StringValue), typeof(UploadHelper));
Sitecore.Diagnostics.Log.Info("FloatValue: " + (cellInfo.FloatValue) + ", " + (cellInfo.FloatValue).ToString(nfi), typeof(UploadHelper));
Sitecore.Diagnostics.Log.Info("StringValueWithoutFormat: " + (cellInfo.StringValueWithoutFormat), typeof(UploadHelper));
Sitecore.Diagnostics.Log.Info("IntValue: " + (cellInfo.IntValue), typeof(UploadHelper));
}
if (Convert.ToDouble(cellInfo.Value).ToString() != value)
{
Double val;
if (Double.TryParse(value, System.Globalization.NumberStyles.Any, nfi, out val))
{
Sitecore.Diagnostics.Log.Info("Using value " + val, typeof(UploadHelper));
obj.Properties.Add(propNames[j], val);
}
else
{
Sitecore.Diagnostics.Log.Info("Failed to parse as decimal, using stringValue " + value, typeof(UploadHelper));
obj.Properties.Add(propNames[j], value);
}
}
else
{
Sitecore.Diagnostics.Log.Info("Value as double matches StringValue", typeof(UploadHelper));
obj.Properties.Add(propNames[j], Convert.ToDouble(cellInfo.Value));
}
}catch(Exception ex)
{
Sitecore.Diagnostics.Log.Info(ex.Message, typeof(UploadHelper));
obj.Properties.Add(propNames[j], cellInfo.StringValue);
}
}
else
{
obj.Properties.Add(propNames[j], cellInfo.StringValue);
}
}
}
else
{
obj.Properties.Add(propNames[j], null);
}
}
list.Add(obj);
}
}
The reason why I added all the additional code for numeric values is because on the German server, cellInfo.StringValue returns an improperly formatted number as a string - it uses periods instead of commas, so large decimal values end up being returned like 12.703.1005 instead of 12,703.1005.
So, I tried to return cellInfo.DoubleValue instead when the cell is numeric, but that ALSO returns wrong. Some decimals like 12.7 are being interpreted as dates, so cellInfo.DoubleValue is entirely wrong, but cellInfo.StringValue gives me the correct number (as a string). But the one thing that's still not working either as strings or decimals is large numbers that have a comma and a decimal.
In the second block of code you can see all the logging I added in. Here is the output on my local, for parsing a value of 2074.927
27908 10:47:59 INFO Value: 2074.927 StringValue: 2074.927 DoubleValue: 2074.927
27908 10:48:02 INFO Convert.ToDouble Value: 2074.927, 2074.927
27908 10:48:04 INFO DoubleValue: 2074.927, 2074.927
27908 10:48:07 INFO StringValue: 2074.927
27908 10:48:10 INFO FloatValue: 2074.927, 2074.927
27908 10:48:21 INFO StringValueWithoutFormat: 2074.9270000000001
27908 10:48:24 INFO IntValue: 2074
and here is the output on the German server:
ManagedPoolThread #12 15:36:04 INFO Value: 2074927 StringValue: 2.074.927 DoubleValue: 2074927
ManagedPoolThread #12 15:36:04 INFO Convert.ToDouble Value: 2074927, 2074927
ManagedPoolThread #12 15:36:04 INFO DoubleValue: 2074927, 2074927
ManagedPoolThread #12 15:36:04 INFO StringValue: 2.074.927
ManagedPoolThread #12 15:36:04 INFO FloatValue: 2074927, 2074927
ManagedPoolThread #12 15:36:04 INFO StringValueWithoutFormat: 2074927
ManagedPoolThread #12 15:36:04 INFO IntValue: 2074927
On the German server, I don't have a single instance of the correct number. It early strips the decimal place (returning the number several orders of magnitude larger than it should be), or it gives me a string value that has a period instead of a comma, which I cannot parse as a decimal.
Why is the German server messing this up? How can I change my code to parse correctly on the German server? As you can see in the code I'm already trying to use NumberFormatInfo to give me the correct delimiters but it doesn't matter since the DoubleValue is returning with no delimeter to begin with.
#Anshul Samaiyar,
If you could specify your custom formatting, i.e., "## ###.##%" for the given value to the cell in MS Excel manually, you will also get this result ("1231123.%"). So, Aspose.Cells works the same way as MS Excel does. Your custom formatting is not right. Please see the following sample code with (updated) custom formatting and give it a try, it will give you expected results.
e.g.
Sample code:
//Create a new (empty) workbook
Workbook workbook = new Workbook();
//Get the first (default) worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
//Get A1 cell
Cell cell = worksheet.getCells().get("A1");
//Specify double value
Double dataValue = 12311.23;
dataValue = Double.parseDouble(dataValue.toString());
cell.putValue(dataValue);
//Create a style and set the custom formattings
Style cellStyle = workbook.createStyle();
cellStyle.setCustom("## ###.##\\%");
//Apply the style to the cell
cell.setStyle(cellStyle);
//Autofit column to show all values
worksheet.autoFitColumn(0);
//Save the Excel file
workbook.save("f:\\files\\out1.xlsx");
//Save to PDF file
workbook.save("f:\\files\\out12.pdf");
Hope this helps, you may also post queries in the dedicated forums.
Facing similar issue where
dataValue = 12311.23;
dataValue = Double.parseDouble(dataValue.toString());
cellStyle.setCustom("## ###.##%");
is not getting change to 12 311.23 but getting g converted to 1231123.% any solution for the issue is welcome.

Word JS APIs: extending a Range

While working on answering this question I would really like to have been able to extend a Range by a specific number of characters. In the COM API I would have used Range.MoveEnd(). Is there any equivalent that I didn't find in the JS API?
Background: The question referenced is about finding search terms with more than 255 characters - which is a limit in Word for the desktop. The search fails.
The simple way to go about it would be to search the first 254 characters, then expand the found Range by the remaining number of characters and comparing that Range.Text to the full search term.
Not finding any equivalent for expanding a Range in this manner, I had to resort to:
breaking down the search term into < 255 character pieces
search for each piece one-by-one
determine whether each searched piece was adjacent to the previous
then expand a Range to include the adjacent piece
and repeat until all pieces were found
Thus, my question...
async function basicSearch() {
await Word.run(async (context) => {
let maxNrChars = 254;
let searchterm = "";
let shortSearch = true; //search string < 255 chars
let fullSearchterm = "Video provides a powerful way to help you prove your point. When you click Online Video, you can paste in the embed code for the video you want to add. You can also type a keyword to search online for the video that best fits your document. Aösdlkvaösd faoweifu aösdlkcj aösdofi "
let searchTermNrChars = fullSearchterm.length;
let nrSearchCycles = Number((searchTermNrChars / maxNrChars).toFixed(0));
let nrRemainingChars = searchTermNrChars - (nrSearchCycles * maxNrChars);
//console.log("Number of characters in search term: " + searchTermNrChars
// + "\nnumber of search cycles required: " + nrSearchCycles
// + "\nremaining number of characters: " + nrRemainingChars);
//numerous ranges are required to extend original found range
let bodyRange = context.document.body.getRange();
bodyRange.load('End');
let completeRange = null;
let resultRange = null;
let extendedRange = null;
let followupRange = null;
let cycleCounter = 0;
let resultText = "";
if (searchTermNrChars > maxNrChars) {
searchterm = fullSearchterm.substring(0, maxNrChars);
cycleCounter++;
shortSearch = false;
}
else { searchterm = fullSearchterm; }
let results = context.document.body.search(searchterm);
results.load({ select: 'font/highlightColor, text' });
await context.sync();
// short search term, highlight...
if (shortSearch) {
for (let i = 0; i < results.items.length; i++) {
results.items[i].font.highlightColor = "yellow";
}
}
else {
//console.log("Long search");
for (let i = 0; i < results.items.length; i++) {
resultRange = results.items[i];
resultRange.load('End');
extendedRange = resultRange.getRange('End').expandTo(bodyRange.getRange('End'));
await context.sync();
//search for the remainder of the long search term
for (let cycle = 1; cycle < nrSearchCycles; cycle++) {
searchterm = fullSearchterm.substring((cycle * maxNrChars), maxNrChars);
//console.log(searchterm + " in cycle " + cycle);
let CycleResults = extendedRange.search(searchterm);
CycleResults.load({ select: 'text, Start, End' });
await context.sync();
followupRange = CycleResults.items[0];
//directly adjacent?
let isAfter = followupRange.compareLocationWith(resultRange);
if (isAfter.value == Word.LocationRelation.adjacentAfter) {
resultRange.expandTo(followupRange);
extendedRange = resultRange.getRange('End').expandTo(bodyRange.getRange('End'));
}
await context.sync();
}
if (nrRemainingChars > 0) {
console.log("In remaining chars");
searchterm = fullSearchterm.substring(searchTermNrChars - nrRemainingChars);
console.log(searchterm);
let xresults = extendedRange.search(searchterm);
xresults.load('end, text');
await context.sync();
let xresult = xresults.items[0];
let isAfter = xresult.compareLocationWith(resultRange);
await context.sync();
console.log(isAfter.value);
if (isAfter.value == Word.LocationRelation.adjacentAfter) {
completeRange = resultRange.expandTo(xresult);
completeRange.load('text');
//completeRange.select();
await context.sync();
resultText = completeRange.text.substring(0, fullSearchterm.length);
console.log("Result" + cycleCounter + ": " + resultText);
}
}
else {
//No remeaining chars
resultRange.load('text');
//resultRange.select();
await context.sync();
resultText = resultRange.text.substring(0, fullSearchterm.length);
completeRange = resultRange;
}
//long search successful?
if (resultText == fullSearchterm) {
completeRange.font.highlightColor = "yellow";
}
else {
console.log("Else! " + resultText + " / " + fullSearchterm);
}
completeRange = null;
}
}
});
That was something we had in the original design, but it was actually removed from the API as it can easily lead to unexpected outcomes (i.e. hidden character inconsistencies, footnotes, etc.), and we could not cover those cases with the resources at hand. We decided to remove it.
That been said I think you can achieve something similar to range.MoveEnd() with Word.js, you just need to define to the end of what ;). One way of doing it is to use the range.expandTo(endRange) method. Again, The interesting thing is how to get the "endRange", so the following example shows how to do it if "end" means the end of the paragraph, probably in your scenario will suffice.
async function run() {
await Word.run(async (context) => {
//assume the range at the end of your 255 characters.
var startRange = context.document.getSelection().getRange("end");
//This one is the range at the end of the paragraph including the selection.
var endRange = context.document.getSelection().paragraphs.getLast().getRange("end");
var deltaRange = startRange.expandTo(endRange);
context.load(deltaRange);
await context.sync();
// this will print the characters after the range all the way to the end of the paragraph.
console.log(deltaRange.text);
});
}
hope this helps or at least sets you up in the right direction.

Swift Type 'string.index' has no subscript members

I'm currently converting C++ code to Swift and I've gotten stuck on one part. The parameter passed into the function is a string and the area where I'm stuck is when attempting to set a variable based on the second to last character of a string to check for a certain character.
The error shows up on this line:
line[i-1]
I've tried casting this value to an Int but this didn't work:
Int(line[i - 1])
I've also tried to see if the string's startIndex function which takes a Int would work but it didn't:
line.startIndex[i - 1]
Here is the full function:
func scanStringForSpecificCharacters(line: String){
var maxOpen: Int = 0;
var minOpen: Int = 0;
minOpen = 0;
maxOpen = 0;
var i = 0
while i < line.characters.count {
for character in line.characters {
//var c: Character = line[i];
if character == "(" {
maxOpen += 1;
if i == 0 || line[i - 1] != ":" {
minOpen += 1;
}
}
else if character == ")"{
minOpen = max(0,minOpen-1);
if i == 0 || line[i-1] != ":"{
maxOpen -= 1;
}
if maxOpen < 0{
break;
}
}
}
if maxOpen >= 0 && minOpen == 0{
print("YES")
}else{
print("NO")
}
}
}
Strings in Swift aren't indexed collections and instead you can access one of four different views: characters, UTF8, UTF16, or unicodescalars.
This is because Swift supports unicode, where an individual characters may actually be composed of multiple unicode scalars.
Here's a post that really helped me wrap my head around this: https://oleb.net/blog/2016/08/swift-3-strings/
Anyway, to answer you question you'll need to create an index using index(after:), index(before:), or index(_, offsetBy:).
In your case you'd want to do something like this:
line.index(line.endIndex, offsetBy: -2) // second to last character
Also, you'll probably find it easier to iterate directly using a String.Index type rather than Int:
let line = "hello"
var i = line.startIndex
while i < line.endIndex {
print(line[i])
i = line.index(after: i)
}
// prints ->
// h
// e
// l
// l
// o
Working with Strings in Swift was changed several times during it's evolution and it doesn't look like C++ at all. You cannot subscript string to obtain individual characters, you should use index class for that. I recommend you read this article:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html
As already pointed out in the other answers, the compiler error
is caused by the problem that you cannot index a Swift String with
integers.
Another problem in your code is that you have a nested loop which is
probably not intended.
Actually I would try to avoid string indexing at all and only
enumerate the characters, if possible. In your case, you can
easily keep track of the preceding character in a separate variable:
var lastChar: Character = " " // Anything except ":"
for char in line.characters {
if char == "(" {
maxOpen += 1;
if lastChar != ":" {
minOpen += 1;
}
}
// ...
lastChar = char
}
Or, since you only need to know if the preceding character is
a colon:
var lastIsColon = false
for char in string.characters {
if char == "(" {
maxOpen += 1;
if !lastIsColon {
minOpen += 1;
}
}
// ...
lastIsColon = char == ":"
}
Another possible approach is to iterate over the string and a shifted
view of the string in parallel:
for (lastChar, char) in zip([" ".characters, line.characters].joined(), line.characters) {
// ...
}
As others have already explained, trying to index into Swift strings is a pain.
As a minimal change to your code, I would recommend that you just create an array of the characters in your line up front:
let linechars = Array(line.characters)
And then anywhere you need to index into the line, use linechars:
This:
if i == 0 || line[i-1] != ":" {
becomes:
if i == 0 || linechars[i-1] != ":" {

Javascript First letter uppercase restlower of two lines "."

I want to first letter to be in upper case other in lower. But after ".", it must be upper again..
function firstToUpperCase( str ) {
return str.substr(0, 1).toUpperCase() + str.substr(1);
}
var str = 'prompt("Enter text to convert: ")
var Upcase = firstToUpperCase( str );
document.write(Upcase);
Here's a simplistic answer based on what you provided. It does not take whitespace into account following the period since you didn't mention that in the specs.
function firstToUpperCase(str) {
var parts = str.split(".");
for (i = 0; i < parts.length; i++) {
parts[i] = parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1).toLowerCase();
}
return parts.join(".");
}
If you're trying to deal with sentences, something like this might be a little better, though it does not preserve exact whitespace:
function firstToUpperCase(str) {
var parts = str.split(".");
for (i = 0; i < parts.length; i++) {
sentence = parts[i].trim();
parts[i] = sentence.substring(0, 1).toUpperCase() + sentence.substring(1).toLowerCase();
}
return parts.join(". ");

Pick up relevant information from a string using regular expression C#3.0

I have been given some file name which can be like
<filename>YYYYMMDD<fileextension>
some valid file names that will satisfy the above pattern are as under
xxx20100326.xls,
xxx2v20100326.csv,
x_20100326.xls,
xy2z_abc_20100326_xyz.csv,
abc.xyz.20100326.doc,
ab2.v.20100326.doc,
abc.v.20100326_xyz.xls
In what ever be the above defined case, I need to pick up the dates only. So for all the cases, the output will be 20100326.
I am trying to achieve the same but no luck.
Here is what I have done so far
string testdata = "x2v20100326.csv";
string strYYYY = #"\d{4}";
string strMM = #"(1[0-2]|0[1-9])";
string strDD = #"(3[0-1]|[1-2][0-9]|0[1-9])";
string regExPattern = #"\A" + strYYYY + strMM + strDD + #"\Z";
Regex regex = new Regex(regExPattern);
Match match = regex.Match(testdata);
if (match.Success)
{
string result = match.Groups[0].Value;
}
I am using c#3.0 and dotnet framework 3.5
Please help. It is very urgent
Thanks in advance.
Try this:
DateTime result = DateTime.MinValue;
System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
var testString = "x2v20100326.csv";
var format = "yyyyMMdd";
try
{
for (int i = 0; i < testString.Length - format.Length; i++)
{
if (DateTime.TryParseExact(testString.Substring(i, format.Length), format, provider, System.Globalization.DateTimeStyles.None, out result))
{
Console.WriteLine("{0} converts to {1}.", testString, result.ToString());
break;
}
}
}
catch (FormatException)
{
Console.WriteLine("{0} is not in the correct format.", testString);
}
This one fetches the last date in the string.
var re = new Regex("(?<date>[0-9]{8})");
var test = "asdf_wef_20100615_sdf.csv";
var datevalue = re.Match(test).Groups["date"].Value;
Console.WriteLine(datevalue); // prints 20100615
Characters \A and \Z - begin and end of the string respectivly.
I think you need pattern like:
string regExPattern = #"\A.*(?<FullDate>" + strYYYY + strMM + strDD + #").*\..*\Z";
".*" - any symbols at the begin
".*\..*" - any symbols before the dot, dot and any symbols after dot
And get a full date:
match.Groups["FullDate"]
You may need to group things in your month and day expressions:
((1[0-2])|(0[1-9))
((3[0-1])|([1-2][0-9])|(0[1-9]))