Regex in Custom package in C# i want capture (meta:resourcekey =".......") - c#

DTE dte = Package.GetGlobalService(typeof(DTE)) as DTE;
TextDocument activeDoc = dte.ActiveDocument.Object() as TextDocument;
var text = activeDoc.CreateEditPoint(activeDoc.StartPoint).GetText(activeDoc.EndPoint);
var input = (text);
var regex = new Regex(#"(\bresourcekey\b+) = ");
var match = regex.Matches(input);
string matches = string.Empty;
foreach(var item in match)
{
matches += item.ToString() + " ";
}
MessageBox.Show(matches);
My regex command are fault(i know)but i want capture meta:resourcekey = "......" from my messagebox text i want only .... part of my capturing.

Here is plain regex
meta:resourcekey[\s]=[\s]\"(.*?)\"
And here is c# Example
var mydata = "meta:resourcekey = \"something\"";
Regex regex = new Regex("meta:resourcekey[\\s]*=[\\s]*\"(.*?)\\\"");
foreach (Match htmlPath in regex.Matches(mydata))
{
Console.WriteLine(htmlPath.Groups[1].Value);
}

DTE dte = Package.GetGlobalService(typeof(DTE)) as DTE;
TextDocument activeDoc = dte.ActiveDocument.Object() as TextDocument;
var text = activeDoc.CreateEditPoint(activeDoc.StartPoint).GetText(activeDoc.EndPoint);
var input = (text);
Regex regex = new Regex(#"(meta:resourcekey)+(\W)+(\w*)+(\W)");
var match = regex.Matches(input);
string matches = string.Empty;
foreach(var item in match)
{
matches += item.ToString() + " ";
}
MessageBox.Show(matches);
I found the answer like that.That makes Scann the current page code and write to text and finally getting meta:resourcekey="something" all of the code pages... Write to MessageBox

Related

Mailkit - replace text in Html part

will appreciate any Help on this one.
I am trying to replace text in an email template using Mailkit. The issue is that in Mailkit there is at least a text part and and Html part.
I can get then set the text part using code such as:
var textPart = message.BodyParts.OfType<TextPart>().FirstOrDefault();
I can get the htmlbody using
var htmlPart = message.htmlBody
but once I modify it I do not know how to set the htmlpart to the message's htmlBody.
My code so far:
FileStream sr = new FileStream(fileLocation + "\\" + fileName, FileMode.Open, FileAccess.Read);
message = MimeMessage.Load(sr);
sr.Close();
//Get the text Part
var textPart = message.BodyParts.OfType<TextPart>().FirstOrDefault();
//Get the HtmlBody
var htmlPart = message.HtmlBody;
string regexPattern;
string regexReplacement;
Regex regexText;
foreach (var replaceSet in replaceArray)
{
regexPattern = "#" + replaceSet["Key"].ToString() + "#";
regexReplacement = (string)replaceSet["Value"].ToString();
//bool test = Regex.IsMatch(docText, regexPattern);
if (regexReplacement != "")
{
regexText = new Regex(regexPattern);
textPart.Text = regexText.Replace(textPart.Text, regexReplacement);
//Set, modify the text part
htmlPart = regexText.Replace(htmlPart, regexReplacement);
}
}
try
{
message.WriteTo(fileLocation + "\\output\\" + fileName);
}
catch (Exception Ex)
{
result = Ex.Message;
return BadRequest(result);
}```
Something like this will probably work:
// Get the text Part
var textPart = message.BodyParts.OfType<TextPart>().FirstOrDefault(x => x.IsPlain);
var htmlPart = message.BodyParts.OfType<TextPart>().FirstOrDefault(x => x.IsHtml);
string regexPattern;
string regexReplacement;
Regex regexText;
foreach (var replaceSet in replaceArray)
{
regexPattern = "#" + replaceSet["Key"].ToString() + "#";
regexReplacement = (string)replaceSet["Value"].ToString();
//bool test = Regex.IsMatch(docText, regexPattern);
if (regexReplacement != "")
{
regexText = new Regex(regexPattern);
textPart.Text = regexText.Replace(textPart.Text, regexReplacement);
//Set, modify the text part
htmlPart.Text = regexText.Replace(htmlPart.Text, regexReplacement);
}
}

How to add a string of text into another txt file

I have this txt file that contains this text:
MSH^~|\&^R3POCQUERYS^050~BCMABU.MED.VA.GOV~DNS^R3POCQUERYR^^201711081317040500^^RQC~I06^50279320^D^2.5^^^AL^NE^USA
QRD^20171108131704-0500^R^I^WQRY^^^^SSN~%ABC123^9A-MED~WA0034^^^T
but I only want the values that come after SSN~% and after the MED~
I want to be able read from the Line that starts with QRD and then be able to grab ANY value after SSN~% and MED~, so the value can be anything I'm just using ABC123 and WA0034 as examples.
Form1.cs
private void Parse(string filename)
{
string line;
var str = File.ReadAllText(filename);
System.IO.StreamReader file = new System.IO.StreamReader(filename);
targetRichTextBox = richTextBox1;
WriteTextSafelyInRichTextBox(str);
while ((line = file.ReadLine()) != null)
{
if ((line.Contains("QRD"))
{
//Enter code here
}
}
char[] delimiterChars = { '^' };
string[] words = str.Split(delimiterChars);
var createText = (RetrunTemplate.Get().Replace(words[24], "VHIC-").Replace(words[25], "9A-MED~WA0034"));
var outputFilename = outputDir + "\\OutboundMessage - " + DateTime.UtcNow.ToString("yyyy-MM-dd HH-mm-ss-ff", CultureInfo.InvariantCulture) + ".txt";
File.WriteAllText(outputFilename, createText);
targetRichTextBox = richTextBox2;
WriteTextSafelyInRichTextBox(createText);
file.Close();
File.Delete(filename);
MessageBox.Show("You have successfuly creatd an outbound Message");
}
RetrunTemplate
class RetrunTemplate
{
public static string Get()
{
string retrunTemplate = #"MSH^~|\&^R3POCSEND^442~CHEY209.FO-BAYPINES.MED.VA.GOV~DNS^R3POCRCV^^20171108131710-0400^^RCL~I06^442157252912^D^2.5^^^AL^NE^USA" + Environment.NewLine +
"PID^^^4420041228V165312~~~USVHA&&0363~NI~VA FACILITY ID&442&L~~20171108|666393848~~~" + Environment.NewLine +
#"USSSA&&0363~SS~VA FACILITY ID&442&L|""~~~USDOD&&0363~TIN~VA FACILITY ID&442&L" + Environment.NewLine +
#"""~~~USDOD&&0363~FIN~VA FACILITY ID&442&L|7209344~~~USVHA&&0363~PI~VA FACILITY ID&442&L" + Environment.NewLine +
#"^VHIC-ABC123~~~USVHA&&0363~PI~VA FACILITY ID&742V1&L^ZEIGLER~PG~EIGHT~~~~L" + Environment.NewLine +
#"|""~~~~~~N^^19220304^M^^^9234234~""~SAN FRANCISCO~CA~94114~USA~P~""~075|~~SAN JOSE~CO~~""~N^^""^^^^^^^^^^^^^^^^^^" + Environment.NewLine +
#"PV1^^^9A-MED" + Environment.NewLine + "HH1^WA0034";
return retrunTemplate;
}
}
Suppose you read the file line by line. You can validate each line against the following Regex, and extract what you want.
var text = "QRD^20171108131704-0500^R^I^WQRY^^^^SSN~%ABC123^9A-MED~WA0034^^^T";
var rgx = new Regex(#"QRD.+SSN~%(.+)MED~(.+)");
var match = rgx.Match(text);
if (match.Success)
{
Console.WriteLine(match.Groups[1].Value);
Console.WriteLine(match.Groups[2].Value);
}
The match.Groups[1] has ABC123^9A-, and match.Groups[2] has WA0034^^^T. You can now do what you will with those text.
Regex Breakdown
#"QRD.+SSN~%(.+)MED~(.+)"
QRD - Starts with the string QRD
.+ - Followed by one or more characters
SSN~% - Followed by SSN~~%
(.+) - Grab (to Groups[1]) one or more characters between SSN~% and MED~
MED! - Followed by MED~
(.+) - Grab everything else in the line to Groups[2]
Here's my effort.
var input = #"MSH^~|\&^R3POCQUERYS^050~BCMABU.MED.VA.GOV~DNS^R3POCQUERYR^^201711081317040500^^RQC~I06^50279320^D^2.5^^^AL^NE^USA
QRD^20171108131704-0500^R^I^WQRY^^^^SSN~%ABC123^9A-MED~WA0034^^^T" ;
var pattern = #"SSN\~\%([A-Z0-9]+).*MED\~([A-Z0-9]+)";
var matches = Regex.Matches(input, pattern, RegexOptions.Multiline).
Select( m => new { SSN = m.Groups[1].Value, MED = m.Groups[2].Value});
foreach(var m in matches ) {
Console.WriteLine($"SSN = {m.SSN}, MED = {m.MED}");
}
Output
SSN = ABC123, MED = WA0034
With QRD matching
var input = #"MSH^~|\&^R3POCQUERYS^050~BCMABU.MED.VA.GOV~DNS^R3POCQUERYR^^201711081317040500^^RQC~I06^50279320^D^2.5^^^AL^NE^USA
QRD^20171108131704-0500^R^I^WQRY^^^^SSN~%ABC123^9A-MED~WA0034^^^T";
var pattern = #"SSN\~\%([A-Z0-9]+).*MED\~([A-Z0-9]+)";
var matches = input
.Split()
.Where(l => l.StartsWith("QRD"))
.Select(l => Regex.Matches(l, pattern).Select(m => new { SSN = m.Groups[1].Value, MED = m.Groups[2].Value }));
foreach (var groups in matches)
{
foreach (var g in groups)
{
Console.WriteLine($"SSN = {g.SSN}, MED = {g.MED}");
}
}
Output
SSN = ABC123, MED = WA0034

replace links in string with my link

i want to replace every link(s) in a string with the link i want to provide. What i have tried is-
StreamReader reader = new StreamReader(dd1.SelectedItem.Value);
string readFile = reader.ReadToEnd();
Regex regx = new Regex("http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\#\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*([a-zA-Z0-9\\?\\#\\=\\/]){1})?", RegexOptions.IgnoreCase);
string output=regx.ToString();
output = readFile;
MatchCollection matches = regx.Matches(output);
foreach (Match match in matches)
{
output = output.Replace(#"match.Value", #"http://localhost:61187/two?" + "sender=" + Server.UrlEncode(this.txtUsername.Text) + "&reciever=" + output);
}
Here, i have a string output which contains some links. So, i have used regex to parse the links in the string. But, the string named "output" is not read and its neither showing an error nor an output.
It seems to me that you should be using regx.Replace(...) instead:
StreamReader reader = new StreamReader(dd1.SelectedItem.Value);
string readFile = reader.ReadToEnd();
Regex regx = new Regex("http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\#\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*([a-zA-Z0-9\\?\\#\\=\\/]){1})?", RegexOptions.IgnoreCase);
string output = regx.ToString();
output = readFile;
string username = Server.UrlEncode(this.txtUsername.Text);
output = regx.Replace(output, new MatchEvaluator((match) =>
{
var url = Uri.EscapeDataString(match.Value);
return $"http://localhost:61187/two?sender={username}&receiver={url}";
}));
This will replace every match with the URL returned by the anonymous function.

Extract all strings between [ text1 ] [text2] tags

I have an sql text that includes
"Select * from Table Where [PARAM1] = [PARAM2] ..."
I want to get list between "[" "]" tags to list.
How can I do it ?
You can do it using LINQ
string str = "Select * from Table Where [PARAM1] = [PARAM2] ...";
string[] Array = str.Split().Where(r=> r.StartsWith("[") && r.EndsWith("]"))
.Select(r=> r.Trim('[',']'))
.ToArray();
Use this snippet
string strRegex = #"\[(.*?)\]";
RegexOptions myRegexOptions = RegexOptions.IgnoreCase;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = #"Select * from Table Where [PARAM1] = [PARAM2] ...";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
// myMatch.Groups[0] - your string
}
You can try using regular expressions and some LINQ:
Regex t = new Regex(#"\[([^]]*)\]");
List<String> parameters = t.Matches(input_string).Cast<Match>().Select(a => a.Groups[1].ToString()).ToList();
This will result in a List holding the two matches PARAM1 and PARAM2
You can also do
List<string> matches=Regex.Matches(#"(?<=\[)[^\[\]]*(?=\])")
.Cast<Match>()
.Select(x=>x.Value)
.ToList();
Here is what you need:
Regex t = new Regex(#"\[(.*?)\]");
string str = #"Select * from Table Where [PARAM1] = [PARAM2] ...";
foreach (Match myMatch in myRegex.Matches(str))
{
// myMatch.Groups[0] and so on....
}
Live Demo
To convert a MatchCollection to List use:
List<Match> myMatches = Regex.Matches("bla", #"\[[^]]*)\]").Cast<Match>.toList();
You can try using this regular expression:
Regex regex = new Regex(#"\[.*?\]");
var parameters = regex.Matches(sqlQueryString);

Saving an XML that has invalid characters

there are code snippets that strip the invalid characters inside a string before we save it as an XML ... but I have one more problem: Let's say my user wants to have a column name like "[MyColumnOne] ...so now I do not want to strip these "[","] well because these are the ones that user has defined and wants to see them so if I use some codes that are stripping the invalid characters they are also removing "[" and "[" but in this case I still need them to be saved... what can I do?
Never mind, I changed my RegEx format to use XML 1.1 instead of XML 1.0 and now it is working good :
string pattern = String.Empty;
//pattern = #"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|7F|8[0-46-9A-F]9[0-9A-F])"; //XML 1.0
pattern = #"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|[19][0-9A-F]|7F|8[0-46-9A-F]|0?[1-8BCEF])"; // XML 1.1
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
if (regex.IsMatch(sString))
{
sString = regex.Replace(sString, String.Empty);
File.WriteAllText(sString, sString, Encoding.UTF8);
}
return sString;
This worked for me, and it was fast.
private object NormalizeString(object p) {
object result = p;
if (p is string || p is long) {
string s = string.Format("{0}", p);
string resultString = s.Trim();
if (string.IsNullOrWhiteSpace(resultString)) return "";
Regex rxInvalidChars = new Regex("[\r\n\t]+", RegexOptions.IgnoreCase);
if (rxInvalidChars.IsMatch(resultString)) {
resultString = rxInvalidChars.Replace(resultString, " ");
}
//string pattern = String.Empty;
//pattern = #"";
////pattern = #"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|7F|8[0-46-9A-F]9[0-9A-F])"; //XML 1.0
////pattern = #"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|[19][0-9A-F]|7F|8[0-46-9A-F]|0?[1-8BCEF])"; // XML 1.1
//Regex rxInvalidXMLChars = new Regex(pattern, RegexOptions.IgnoreCase);
//if (rxInvalidXMLChars.IsMatch(resultString)) {
// resultString = rxInvalidXMLChars.Replace(resultString, "");
//}
result = string.Join("", resultString.Where(c => c >= ' '));
}
return result;
}

Categories