I have string:
string mystring = "hello(hi,mo,wo,ka)";
And i need to get all arguments in brackets.
Like:
hi*mo*wo*ka
I tried that:
string res = "";
string mystring = "hello(hi,mo,wo,ka)";
mystring.Replace("hello", "");
string[] tokens = mystring.Split(',');
string[] tokenz = mystring.Split(')');
foreach (string s in tokens)
{
res += "*" + " " + s +" ";
}
foreach (string z in tokenz)
{
res += "*" + " " + z + " ";
}
return res;
But that returns all words before ",".
(I need to return between
"(" and ","
"," and ","
"," and ")"
)
You can try to use \\(([^)]+)\\) regex get the word contain in brackets,then use Replace function to let , to *
string res = "hello(hi,mo,wo,ka)";
var regex = Regex.Match(res, "\\(([^)]+)\\)");
var result = regex.Groups[1].Value.Replace(',','*');
c# online
Result
hi*mo*wo*ka
This way :
Regex rgx = new Regex(#"\((.*)\)");
var result = rgx.Match("hello(hi,mo,wo,ka)");
Split method has an override that lets you define multiple delimiter chars:
string mystring = "hello(hi,mo,wo,ka)";
var tokens = mystring.Replace("hello", "").Split(new[] { "(",",",")" }, StringSplitOptions.RemoveEmptyEntries);
Related
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
I need to remove a pattern from a string, I think regex could do the job, but I'm having trouble solving this.
The pattern must be in the end of the string.
string fileName = "File (123)";
string pattern = " (0)";
string cleanName = PatternRemover(fileName, pattern);
//Should result in: cleanName == "File"
Edit:
Ok, here is the code that I'm using now after your answers:
public static string GetNextFilePath2(string fullPath, ref uint id, string idFormat)
{
string dir = Path.GetDirectoryName(fullPath);
string ext = Path.GetExtension(fullPath);
string fileNameNoExt = Path.GetFileNameWithoutExtension(fullPath);
if (ext.Length > 0 && ext[0] != '.')
ext = "." + ext;
string baseName = Regex.Replace(fileNameNoExt, #"\s\(\d+\)", "");
string fileName = baseName + " (" + id.ToString(idFormat) + ")" + ext;
string path = Path.Combine(dir, fileName);
while (File.Exists(path))
{
id++;
fileName = baseName + " (" + id.ToString(idFormat) + ")" + ext;
path = Path.Combine(dir, fileName);
}
return path;
}
It works, but:
It always start to count from id, I think it may be better to start
from the file name number.
I was hopping to use something like "(0)" as a method parameter that would indicate the pattern to be removed and also the "(" would be parametrized. I'm doing it "manually" now on this line: string fileName = baseName + " (" + id.ToString(idFormat) + ")" + ext;
You can do that without REGEX like:
string newFileName = new String(fileName
.Where(r => !char.IsDigit(r)
&& r != '('
&& r != ')'
&& r != ' ').ToArray());
This would give you File.jpg
If you only want to get the file name then you can use:
string fileNameWithoutPath = Path.GetFileNameWithoutExtension(newFileName);
// it would give you `File`
Using regex:
var subject = "File (123).jpg";
var fileNameWithExtension = Regex.Replace(subject,#"\s*\(\d+\)","");
var fileNameWithoutPath = Path.GetFileNameWithoutExtension(fileNameWithExtension);
And thanks for #habib, I'd not have come with Path.GetFileNameWithoutExtension in this for stripping the extension.
You could use:
\s\(\d+\)\.jpg
assuming you do actually want the extension removed and the extension is always ".jpg". Otherwise:
\s\(\d+\)
Looks for a set of digits in brackets proceeded by a space.
Imagine we have a string as :
String mystring = "A,B,C,D";
I would like to add an apostrophe before and after each word in my string.Such as:
"'A','B','C','D'"
How can i achieve that?
What's your definition of a word? Anything between commas?
First get the words:
var words = mystring.Split(',');
Then add the apostrophes:
words = words.Select(w => String.Format("'{0}'", w));
And turn them back into one string:
var mynewstring = String.Join(",", words);
mystring = "'" + mystring.replace(",", "','") + "'";
I would let each "word" be determined by the regex \b word boundary. So, you have:
var output = Regex.Replace("A,B,C,D", #"(\b)", #"'$1");
string str = "a,b,c,d";
string.Format("'{0}'", str.Replace(",", "','"));
or
string str = "a,b,c,d";
StringBuilder sb = new StringBuilder(str.Length * 2 + 2);
foreach (var c in str.ToCharArray())
{
sb.AppendFormat((c == ',' ? "{0}" : "'{0}'"), c);
}
str = sb.ToString();
string mystring = "A,B,C,D";
string[] array = mystring.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string newstring = "";
foreach (var item in array)
{
newstring += "'" + item + "',";
}
newstring = newstring.Remove(newstring.Length - 1);
Console.WriteLine(newstring);
Output will be;
'A','B','C','D'
Here a DEMO.
Or more simple;
string mystring = "A,B,C,D";
Console.WriteLine(string.Format("'{0}'", mystring.Replace(",", "','")));
you can use regular expressions to solve this problem
like this:
string words= "A,B,C,D";Regex reg = new Regex(#"(\w+)");words = reg.Replace(words, match=> { return string.Format("'{0}'", match.Groups[1].Value); });
How can I convert this list of strings to comma separated value enclosed within quotes without any escape characters?
{"apple", "berry", "cherry"} => well, ""apple", "berry", "cherry""
If I understood you correctly,
"\"" + String.Join("\", \"", new string[]{"apple","berry","cherry"}) + "\"";
or, alternatively,
String.Format("\"{0}\"", String.Join("\", \"", new string[] {"apple","berry","cherry"}));
Read more on System.String.Join(...).
Hope this will do the job
var ar = new []{ "apple", "berry", "cherry" };
var separator = "\",\"";
var enclosingTag = "\"";
Console.WriteLine ( enclosingTag + String.Join(separator, ar) + enclosingTag );
If you are using C#:
using System;
string[] arr = new string[] { "apple", "berry", "cherry" };
string sep = "\",\"";
string enclosure = "\"";
string result = enclosure + String.Join(sep, arr) + enclosure;
I currently have the following code:
string user = #"DOMAIN\USER";
string[] parts = user.Split(new string[] { "\\" }, StringSplitOptions.None);
string user = parts[1] + "#" + parts[0];
Input string user can be in one of two formats:
DOMAIN\USER
DOMAIN\\USER (with a double slash)
Whats the most elegant way in C# to convert either one of these strings to:
USER#DOMAIN
Not sure you would call this most elegant:
string[] parts = user.Split(new string[] {"/"},
StringSplitOptions.RemoveEmptyEntries);
string user = string.Format("{0}#{1}", parts[1], parts[0]);
How about this:
string user = #"DOMAIN//USER";
Regex pattern = new Regex("[/]+");
var sp = pattern.Split(user);
user = sp[1] + "#" + sp[0];
Console.WriteLine(user);
A variation on Oded's answer might use Array.Reverse:
string[] parts = user.Split(new string[] {"/"},StringSplitOptions.RemoveEmptyEntries);
Array.Reverse(parts);
return String.Join("#",parts);
Alternatively, could use linq (based on here):
return user.Split(new string[] {"/"}, StringSplitOptions.RemoveEmptyEntries)
.Aggregate((current, next) => next + "#" + current);
You may try this:
String[] parts = user.Split(new String[] {#"\", #"\\"}, StringSplitOptions.RemoveEmptyEntries);
user = String.Format("{0}#{1}", parts[1], parts[0]);
For the sake of adding another option, here it is:
string user = #"DOMAIN//USER";
string result = user.Substring(0, user.IndexOf("/")) + "#" + user.Substring(user.LastIndexOf("/") + 1, user.Length - (user.LastIndexOf("/") + 1));