I have tried to do some research, but everything that I find does not cover what my current dilemma is.
String manipulation is basic right? But here is my problem, I am grabbing an email body from gmail, the body looks something like this (after removing all the HTML formatting, and is a constant string):
Name : Testy Von Test
Cell 1111111111
email testy#testy
Now I need to find the string "Name" and then use trimming to get the full name, but how do I distinguish between this? how do I tell my coding to look for everything from name until Cell and take everything from there? I really did try to find the solution as I believe I am just missing some logic in my mind. If you just give me a link to an article I will be happy to read up and apply the logic myself (I am not expecting anyone to do my work for me), I just need a proper nudge in the right direction please.
Thank you kindly in advance.
(as an edit if anyone should follow this question, look at all the answers, there are a bunch of amazing answers and ideas)
The string you have doesn't seem very well formatted. Name is followed by a colon, Cell is not... this could get very tricky...
but a simple solution using substring.
var s = "Name : Testy Von Test Cell 1111111111 email testy#testy";
var name = s.Substring(
s.IndexOf(":")+1,
s.IndexOf("Cell")-s.IndexOf(":")-1);
Is your mail body always in the exact format?
You can for instance do as shown in this jsfiddle.
var mailbody = 'Name : Testy Von Test Cell 1111111111 email testy#testy';
var nameregex = /Name(.+?)Cell/
var match = nameregex.exec(mailbody);
console.log(match[1]); // Outputs " : Testy Von Test "
In your example it would capture, as seen in the console input, " : Testy von test ". And you can then manipulate it however you'd like. You can also modify the regex with additional options, depending on how your mail outputs vary.
var mailbody = 'Name : Testy Von Test Cell 1111111111 email testy#testy';
var nameregex = /Name\s:\s(.+?)\sCell/
var match = nameregex.exec(mailbody);
console.log(match[1]); // Outputs "Testy Von Test"
What about this:
int start = myString.IndexOf("Name") + "Name : ".Length;
int len = myString.IndexOf("Cell") - start;
string res = myString.Substring(start, len);
Alternativly via Regex:
Regex r = new Regex("Name(.*)Cell");
string res = r.Matches[0].Value;
Related
So, the string I need to implement is this, I am using .Net 4.5.2 in c# in visual studio 2019, I want the espected output to be exactly as below albeit with FIRSTNAME being replaced by a variable.
beneficiaryFirstName: \\\"FIRSTNAME\\\"
This is being used with a lot of similarly structured strings to join them together to form a large graphQL query. The problem I have is that VStudio keeps throwing up errors.
Edit : I would like to make clear, I need the \'s in the string result, and I need FIRSTNAME to be treated as a variable.
I have attempted to use this.
$#"beneficiaryFirstName: \\\"{{FIRSTNAME}}\\\""
But get told that it there's unexpected characters "" and "".
What is the best way around this?
You just need the right escaping
var FIRSTNAME = "Bob";
var pad = #"\\\";
var test1 = $"beneficiaryFirstName: \\\\\\\"{FIRSTNAME}\\\\\\\"";
var test2 = #$"beneficiaryFirstName: \\\""{FIRSTNAME}\\\""";
var test3 = $"beneficiaryFirstName: {pad}\"{FIRSTNAME}{pad}\"";
Console.WriteLine(test1);
Console.WriteLine(test2);
Console.WriteLine(test3);
Output
beneficiaryFirstName: \\\"Bob\\\"
beneficiaryFirstName: \\\"Bob\\\"
beneficiaryFirstName: \\\"Bob\\\"
Disclaimer, I am not sure if the quotes are correct in your example, they seem like they are in weird places, though that could be just how it is
you can do like this.
string FIRSTNAME = "YourName";
string temp = $"beneficiaryFirstName: {FIRSTNAME}";
Console.WriteLine(temp);
It will print
beneficiaryFirstName: YourName
You can try this string temp = $"beneficiaryFirstName: \\\\{FIRSTNAME}\\\\"; if you want outout
beneficiaryFirstName: \\YourName\\
As mentioned by the OP, you can use this to get the required output.
string temp = #$"beneficiaryFirstName: \\\{FIRSTNAME}\\\";
I would like to find match
I prefer to "IndexOf" (not RegExp or something, becuase it is pretty simple codes).
I have a problem with strange character.
The situation is Given, I can not control it.
Let's see the screenshot, that is good enough.
It should make result "-1" but it makes not "-1" (0 in this case).
Thanks.
string myString1 = "abc";
string myString2 = "abc�";
MessageBox.Show(
"Result \n" +
myString1.IndexOf(myString2));
enter image description here
You should be using StringComparison.Ordinal
string myString1 = "abc";
string myString2 = "abc�";
MessageBox.Show("Result \n" + myString1.IndexOf(myString2, StringComparison.Ordinal));
It's just on of those weird "gotchas" that shows using culture information can sometimes really matter.
SOLVED! Ended up using this to do what I wanted:
if (output.Contains("<%TABLE#"))
{
string pattern = #"<%TABLE#([0-9]+)%%>";
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(output, pattern, options))
{
int objectID = Int32.Parse(Regex.Match(m.Value, #"\d+").Value);
output = output.Replace(m.Value, ConvertFunction(objectID));
}
}
In some parts of my SQL data (rendered by a C#/ASP.NET website front-end) are strings, many of which can contain a pattern like <%TABLE#[NUMBER]%%> - [NUMBER] is always a specific ID, 1+. An example in one string would look like <%TABLE#3%%>. Sometimes there may be more than one of these patterns in the same string. I am ultimately trying to do the following:
Find all instances in the string where the pattern occurs
For each instance, call another building function using the # that is present - it takes that # and produces a NewString
Replace that instance of the code with NewString
I do this because each of the SQL tables has a website page to show the data within to the end-user. The way I format the data differs from table to table, so I have a Class for each table that builds the output string and returns it where needed. Sometimes, I need to display an object from a different table within the current one. To try and solve this, I added the above formula within the string, in the specific spot I want the object to be rendered, in the hopes of identifying it and using the ID within to grab the appropriate object, build it, then replace that pattern.
I'm guessing I'll have to use Regex or something to identify the string, but I'm struggling on the best way to grab the pattern, identify the number within, call the function to render the output text using said number, and then replace that specific pattern with the results.
Below are some example inputs and what the output should be. The function ConvertFormula takes in an INT and outputs a STRING.
EXAMPLE INPUTS/EXPECTED OUTPUT
Example 1:
"Here's some data and more stuff.<%TABLE#3541%%>Here is more text.
<%TABLE#31214%%>And some more."
Output 1:
"Here's some data and more stuff." + ConvertFormula(3541) + "Here is more text." + ConvertFormula(31214) + "And some more."
Example 2:
"Here's some data and more stuff! Maybe more here!<%TABLE#2%%>Here is more text."
Output 2:
"Here's some data and more stuff! Maybe more here!" + ConvertFormula(2) + "Here is more text."
Example 3:
"<%TABLE#2%%>This is something completely different with the object call at the start.<TABLE#52%%> and another here."
Output 3:
ConvertFormula(2) + "This is something completely different with the object call at the start." + ConvertFormula(52) + " and another here."
Example 4:
"There's nothing in this one, no code to find. Just has some text."
Output 4:
"There's nothing in this one, no code to find. Just has some text."
Example 5:
"This one goes on for a while, like 5132854123 characters, then has a single call right here.<%TABLE#112%%>"
Output 5:
"This one goes on for a while, like 5132854123 characters, then has a single call right here." + ConvertFormula(112)
Example 6:
"Short <%TABLE#412%%> one."
Output 6:
"Short " + ConvertFormula(412) + " one."
Example 7:
"Nothing here again."
Output 7:
"Nothing here again."
I'm guessing that this expression might simply work,
<%TABLE#([0-9]+)%%>
which we would use a capturing group and collect our desired IDs.
Demo
Test
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = #"<%TABLE#([0-9]+)%%>";
string input = #"<%TABLE#3%%>
<%TABLE#1213%%>";
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(input, pattern, options))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
}
string text = "Today is a good day for help. **David Diaz He went to school. **David Diaz like apple. ";
How to get how many times the text **David Diaz occurs in the string text?
UPDATED MY QUESTION
By using StartWhith you can check if the string starts whit ** if it is take the first two words of the string whits will represent the name
string text = "**David Diaz He went to school.";
if (text.StartsWith("**"))
{
var names = text.Split(' ')
.Take(2)
.ToArray();
var fullName = names[0] + " " + names[1];
}
UPDATE
As you said in the commend you want to look how many David Diaz occurs in one string, you can use regex for that.
string text = "Today is a good day for help. **David Diaz He went to school. **David Diaz like apple. ";
int matches = Regex.Matches(
text,
#"(?:\S+\s)?\S*David Diaz\S*(?:\s\S+)?",
RegexOptions.IgnoreCase
).Count;
var text = "Today is a good day for help. **David Diaz He went to school. **David Diaz like apple. ";
var pos = 0;
var num = 0;
var search = "**David Diaz";
while ((pos = text.IndexOf(search, pos)) > -1)
{
num ++;
pos += search.Length;
}
Console.WriteLine(num);
you can try out this in dotnetfiddle
Updated Answer:
It sounds like you want to find the number of times a substring exists in your text. For that, you'll want to use RegEx.Matches, as explained in this answer: https://stackoverflow.com/a/3016577/682840
or LINQ, as explained in this answer: https://stackoverflow.com/a/541994/682840
Original Answer:
.StartsWith returns true/false if the string begins with the search string you provide. If you're wanting to know where a substring exists within your text, you'll need to use .IndexOf or a Regular Expression for more advanced scenarios.
IndexOf will return the location in the text where your provided search string starts (or -1 if it isn't found).
First off, I am not a c# person, so please bear with me on this one.
I need to replace the occurrences of "D:" with "d$" on a script task within SSIS. I sure use the replace function to do this, but the problem is, that this is having unintended consequences on another line.
For example, the script task sends out an email and the header of the email reads as \servername\d$ \further_path. The body of the email reads "UID: 1 : MESSAGE"
The line of code that sends the email reads like:
myHtmlMessage = new MailMessage(Dts.Variables["MailFromAddress"].Value.ToString(), Dts.Variables["MailRecipients"].Value.ToString(), Dts.Variables["MailSubjectSuccess"].Value.ToString(), Dts.Variables["MailBodySuccess"].Value.ToString().Replace("D:", #"\d$ "));
The current output that I get is:
Server Start Time: 3/21/2017 7:25:33 AM
Server End Time: 3/21/2017 7:27:39 AM
Total Run Time: 00:02:06.9402516
Log Folder: \\ServerNamed$\Apps\SSIS\Logs\
UId$ 2 -
The intended output is:
Server Start Time: 3/21/2017 7:25:33 AM
Server End Time: 3/21/2017 7:27:39 AM
Total Run Time: 00:02:06.9402516
Log Folder: \\ServerNamed$\Apps\SSIS\Logs\
UID: 2 -
Look at the log folder line and the UID line
When I use the replace function, the body line gets affected as well with the d$ symbol and that is what I am trying to avoid. Can I write a conditional REPLACE function in C# or, is there any other way to deal with this?
Thanks,
RV.
Have you looked into regular expressions?
https://msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.110).aspx
Here's an example of how you would use it... note that I haven't tested this to determine if it fully functions, but it should help you get started down this path:
E.G.
// Assign your strings into variables to make your code cleaner:
string fromAddress = Dts.Variables["MailFromAddress"].Value.ToString();
string recipients = Dts.Variables["MailRecipients"].Value.ToString();
string subject = Dts.Variables["MailSubjectSuccess"].Value.ToString();
string body = Dts.Variables["MailBodySuccess"].Value.ToString();
// Replace D: in body
string pattern = "(Log Folder.+)D:"; // Capture the D: only if it's on the Log Folder line.
string replacement = "$1\\d$ "; // What we're replacing with.
Regex rgx = new Regex(pattern);
body = rgx.Replace(body, replacement);
// Build my HTML message.
myHtmlMessage = new MailMessage(fromAddress, recipients, subject, body);
I hope this helps...
Note - you can learn much more about regular expression syntax at http://www.regular-expressions.info/ . It's worth looking into if you want to learn how these engines work, how they might differ, and the best syntax to use for finding specific expressions under certain context.
Something along these lines will probably get you there:
string x = "Server Start Time: 3/21/2017 7:25:33 AM" +
"Server End Time: 3 / 21 / 2017 7:27:39 AM" +
"Total Run Time: 00:02:06.9402516" +
#"Log Folder: \\ServerNameD:\Apps\SSIS\Logs\" + Environment.NewLine +
"UID: 2 - ";
int lastNewlinw = x.LastIndexOf(Environment.NewLine);
string beginning = x.Substring(0, lastNewlinw).Replace("D:", #"\d$");
string result = string.Concat(beginning, x.Substring(lastNewlinw + 1, x.Length - beginning.Length));