C# Finding numerical value from specific string - c#

I have a string of varying length that I am trying to retrieve a number from. The format of the string is always:
"some text lines
FC = 1234
more text here
and so on"
So I know the string of numbers comes after "FC = ", and I know it finishes at the next \n. How can I return this number (which will vary in size) into a new string?

Try the following code snippet:
var str = "some text lines \nFC = 1234\n more text here and so on";
Console.WriteLine(Regex.Match(str, #"\d+\.*\d*").Value);

Thanks to all. Think I managed to find a way with Regex, based on ScareCrow's suggestion:
string rgSearch = searchString + #"\d+\.*\d*";
FC = Regex.Match(diagnostics, rgSearch).Value;
FC = FC.Replace(searchString, ""); //Leaves the number only

Related

Remove specific entire word from a string

I have this text file that contains these 3 lines:
Bob
MikeBob
Mike
How could I remove 'Mike' without removing 'Mike' from 'MikeBob'?
I have tried this:
string text = File.ReadAllText("C:/data.txt");
text = text.Replace("Mike", "");
But it removed all occurrences of Mike.
What should I do?
var text = Regex.Replace(File.ReadAllText("C:/data.txt"), "\bMike\b","");
Pretty easy through regex.
// input string
String str = "Hello.???##.##$ here,#$% my%$^$%^&is***()&% this";
// similar to Matcher.replaceAll
str = Regex.Replace(str,#"[^\w\d\s]","");

Remove characters from C# string not belonging to a specicif code page

In C# I have a string that goes on to be inserted into a db table using codepage 37 US. So for instance, the '€' will cause the insert operation to fail.
What is a good way to clean my string of characters not represented in code page 37 and possible replace those charaters with some default character?
Something like this?
var euroString = "abc?€./*";
var encoding37 = System.Text.Encoding.GetEncoding(
37,
new EncoderReplacementFallback("_"), //replacement char
new DecoderExceptionFallback());
var byteArrayWithFallbackChars = encoding37.GetBytes(euroString);
var utfStringFromBytesWithFallback = new string(encoding37.GetChars(byteArrayWithFallbackChars));
//returns "abc?_./*"
P.S.: you can just use GetEncoding(37), but in this case replacement char is ? which I think is not really OK for DB :)
Here is a regex to restrict input to a range of allowed characters:
https://dotnetfiddle.net/WIrSSO
const string Allowed = #"1-9\."; //Add allowed chars here
string cleanStr = Regex.Replace("£1.11", "[^" + Allowed + "]", "");

Insert space between numbers in Textbox

Hello and Thanks for reading.
I have this TextBox where a user can type in his/her Phone number.
<asp:TextBox runat="server" ID="txtPhone" CssClass="TicketField FieldWidthH txtboxStyle" />
If the user types 12345678 I would like it to auto "show" 12 34 56 78 so there is a space after each 2 numbers.
Here is my C# code:
if (IsPostBack) {
if (!string.IsNullOrEmpty(txtPhone.Text)) {
// Check if the value contains any non-numeric values and strip them out
string cleanedUpTextBoxValue = Regex.Replace(txtPhone.Text, #"^\d{6}$", "");
// Parse your number as an integer from your TextBox (after cleaning it up)
Int64 yourIntegerTextBoxValue = Int64.Parse(cleanedUpTextBoxValue);
// Format your number as a string
string formattedResult = yourIntegerTextBoxValue.ToString("## ## ## ##");
// Output the result into your TextBox
txtPhone.Text = formattedResult;
}
}
I also tried string cleanedUpTextBoxValue = Regex.Replace(txtPhone.Text, "[^\d]", "");
But then I type in the Textbox I still only displays the numbers as 12345678.
What am i doing wrong?
Thanks for your time
I'd generally recommend using JavaScript for this if possible, but if you want a C# solution, you can use this to strip out non-digit characters:
string text = Regex.Replace(txtPhone.Text, #"\D", "");
And then this to insert spaces around each pair of digits:
text = Regex.Replace(text, #"\d\d(?!$)", "$0 ");
txtPhone.Text = text;
If implemented in JavaScript, it would look a little bit like this:
text = text.replace(/\D/g, '').replace(/(\d\d)(?!$)/g, '$1 ')
Use the Insert method of string.
string phone = txtPhone.Text; // or your cleaned-up string
phone = phone.Insert(2, " ");
txtPhone.Text = phone;
You can put a loop in there to get spaces between every other digit as needed. Looping over the length of the string, starting from the end, is probably the easiest. Check the length of the string to determine your starting position (i.e., the last character or next to last). What happens if the user enters an odd number of digits?

how do I replace part of text in textbox in c#

I have a problem about using c# in word automation.
My problem is I want to replace part of text in a textbox,
ex: "ABC 12345" and replace 12345 by "123", as a result, "ABC 123"
But I don't know how to get part of text in textbox, I use
object firstshape = 1;
string text = w_Doc.shapes.get_Item(ref firstshape).TextFrame.TextRange.Text;
to get the original text in textbox,but i don't know how to get the range of part text.
Is there any solution to get any range of text in textbox? thanks a lot in advance!!!
You can use replace like this
string Replace = "12345";
string ReplaceWith = "123"
text = text.Replace("12345","123")
To get last 5 characters use this:
string text = w_Doc.shapes.get_Item(ref firstshape).TextFrame.TextRange.Text;
text = text.Substring(text.Length - 5, 5);
text = text.Replace(text, "123"); //to replace
Use Linq
string text = "ABC 12345";
string toReplace = text.Split().SkipWhile(x => x == "ABC").First();

Split string value in C#

I have a string value which I need to get the middle bit out of, e.g. "Cancel Payer" / "New Paperless".
These are examples of the string format:
"REF_SPHCPHJ0000057_Cancel Payer_20100105174151.pdf"
"REF_SPHCPHJ0000056_New Paperless_20100105174151.pdf"
Use:
string s = "REF_SPHCPHJ0000057_Cancel Payer_20100105174151.pdf";
string middleBit = s.Split('_')[2];
Console.WriteLine(middleBit);
The output is
Cancel Payer
This is a place for regular expressions:
Regex re = new Regex(#".*_(?<middle>\w+ \w+)_.*?");
string name = "REF_SPHCPHJ0000057_Cancel Payer_20100105174151.pdf";
string middle = re.Match(name).Groups["middle"].Value;
I think that the regular expression
Regex re = new Regex(#"\w+_\w+_(?<searched>.*)_\d*.pdf");
will meet your needs, if the PDF files always come to you as:
REF_<text>_<your text here>_<some date + id maybe>.pdf

Categories