how to split below value and append AND between values ?
I cannot Split with Space as there is spaces between words
"\"Mark John\" \"Tina Roy\""
as
"\"Mark John\" AND \"Tina Roy\""
In the end it should look like -
"Mark John" AND "Tina Roy"
Any help is appreciated.
string operatorValue = " AND ";
if (!string.IsNullOrEmpty(operatorValue))
{
foreach (string searchVal in SearchRequest.Text.Split(' '))
{
if (!string.IsNullOrEmpty(searchVal))
searchValue += searchVal + operatorValue;
}
}
int index = searchValue.LastIndexOf(operatorValue);
if (index != -1)
{
outputSearchValue = searchValue.Substring(0, index);
}
Try
var result = str.Replace("\" \"","\" And \"");
If you have more than one name, or there is a possibility that you could have more than one whitespace between two names, you could opt for Regex.
var result = Regex.Replace(str,"\"\\s+\"","\" And \"");
Example,
var str = "\"Mark John\" \"Tina Roy\" \"Anu Viswan\"";
var result = Regex.Replace(str,"\"\\s+\"","\" And \"");
Output
"Mark John" And "Tina Roy" And "Anu Viswan"
Or use Regular Expressions:
var test = "\"John Smith\" \"Bill jones\" \"Bob Norman\"";
Console.WriteLine(Regex.Replace(test, "\" \"", "\" AND \""));
Instead of splitting, replace the " " with " AND "
var test = "\"Mark John\" \"Tina Roy\"";
var new_string= test.Replace("\" \"", " AND ");
Related
I am trying to search in titles matching entire search terms.
My example is something like below
string exampleTitle = "apple orange banana";
string term1 = "app bana";
string term2 = "bana app";
string pattern1 = #term1.Replace(" ", "*.*") + "*"; //output:app*.*bana*
string pattern2 = #term2.Replace(" ", "*.*") + "*"; //output:bana*.*app*
//now test
bool isMatch1 = Regex.IsMatch(exampleTitle , pattern1) // true
//now test
bool isMatch2 = Regex.IsMatch(exampleTitle , pattern2) // false
Thus pattern2 not match because banana comes after apple. However I need to true when matching all of words in search term without any order.
Regular expressions can be tricky here. Use this approach instead:
String exampleTitle = "apple orange banana";
String terms = "app bana";
Boolean found = true;
// let's clean things up for malformed input with RemoveEmptyEntries
foreach (String term in terms.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries))
found &= exampleTitle.Contains(term);
Using LINQ instead:
// let's clean things up for malformed input with RemoveEmptyEntries
String[] terms = terms_list.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
Boolean found = terms.All(term => exampleTitle.Contains(term));
You can use the regular expression (?=.*app)(?=.*bana) instead:
string pattern1 = "(?=.*"+term1.Replace(" ", ")(?=.*") + ")"; //output:(?=.*app)(?=.*bana)
string pattern2 = "(?=.*" + term2.Replace(" ", ")(?=.*") + ")"; //output:(?=.*app)(?=.*bana)
You can limit backtracking and forward search with this:
string pattern1 = "(?=(?>.*?"+term1.Replace(" ", "))(?=(?>.*?") + "))"; //output:(?=(?>.*?app))(?=(?>.*?bana))
string pattern2 = "(?=(?>.*?" + term2.Replace(" ", "))(?=(?>.*?") + "))"; //output:(?=(?>.*?app))(?=(?>.*?bana))
I need to true when matching all of words in search term without any order
This could be more clearly expressed as:
bool isMatch = Regex.IsMatch(exampleTitle, ".*app.*") && Regex.IsMatch(exampleTitle, ".*bana.*);
As noted in the other answer, there are non-regex ways to do substring matching that may be more appropriate.
I make a CSV converter, for this, I need to replace all the spaces with ";". I have already did this step. The problem is that I have a texbox with the multiline mod. Here is my actual code :
string[] Espace1 = new string[] { " " };
foreach (string contenu in content1.Split(Espace1, StringSplitOptions.RemoveEmptyEntries))
{
content1 = content1.Replace(" ", ";");
File.WriteAllText(path1, content1);
}
Here is the output : (an example)
15;16;13;21
15;49;47
46;78;15
So that the file is well interprets like a csv I need to add a ";" at the end of each line. Like :
15;16;13;21;
15;49;47;
46;78;15;
Any help ? :)
EDIT
Here is my complete code :
string nom = tbxNom.Text;
#region Normal
try
{
string content1 = tbxArret.Text;
string path1 = #"C:\Users\DanyWin\Desktop\CsvOutput\" + nom + ".csv";
string[] Espace1 = new string[] { " " };
foreach (string contenu in content1.Split(Espace1, StringSplitOptions.RemoveEmptyEntries))
{
content1 = content1.Replace(" ", ";");
File.WriteAllText(path1, content1);
}
}
catch
{
lblInfo.Text = "Erreur";
}
content1 seems to contain the whole file.
So if you want to add semicolons to each line, you could replace the newline with a semicolon and a newline.
content1 = content1.Replace("\n", ";\n");
You can make your code a bit easier:
string nom = tbxNom.Text;
#region Normal
try
{
string content1 = tbxArret.Text;
string path1 = #"C:\Users\DanyWin\Desktop\CsvOutput\" + nom + ".csv";
var lines = content1.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
.Select(line => Regex.Replace(line, #"\s+", ";") + ";");
content1 = String.Join("\n", lines);
File.WriteAllText(path1, content1);
}
catch
{
lblInfo.Text = "Erreur";
}
content1 = string.Concat( content1.Replace(" ", ";"), ";");
Remove all spaces then concat ";" at end
char []split = new char[]{' '};
//replaces all " " with ";", contiguous " " will be replaced with a single ";"
var c2 = String.Join(";", content1.Split(split, StringSplitOptions.RemoveEmptyEntries));
//replaces all newlines with a semicolon followed by a newline, thus appends a semicolon to the end of line.
var c3 = c2.Replace(System.Environment.NewLine, ";"+System.Environment.NewLine);
//If the file did not end with an NewLine, append a semicolon to the last line
if (!c3.EndsWith(System.Environment.NewLine)) c3+=";";
File.WriteAllText(path, c3);
It's not the fastest solution, but it works.
I'm trying to replace a string in C# with the class Regex but I don't know use the class properly.
I want replace the next appearance chain in the String "a"
":(one space)(one or more characters)(one space)"
by the next regular expression
":(two spaces)(one or more characters)(three spaces)"
Will anyone help me and give me the code and explains me the regular expresion used?
you can use string.Replace(string, string)
try this one.
http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx
try this one
private String StrReplace(String Str)
{
String Output = string.Empty;
String re1 = "(:)( )((?:[a-z][a-z]+))( )";
Regex r = new Regex(re1, RegexOptions.IgnoreCase | RegexOptions.Singleline);
Match m = r.Match(Str);
if (m.Success)
{
String c1 = m.Groups[1].ToString();
String ws1 = m.Groups[2].ToString() + " ";
String word1 = m.Groups[3].ToString();
String ws2 = m.Groups[4].ToString() + " ";
Output = c1.ToString() + ws1.ToString() + word1.ToString() + ws2.ToString() + "\n";
Output = Regex.Replace(Str, re1, Output);
}
return Output;
}
Using String.Replace
var str = "Test string with : .*. to replace";
var newstr = str.Replace(": .*. ", ": .*. ");
Using Regex.Replace
var newstr = Regex.Replace(str,": .*. ", ": .*. ");
I would appreciate help with non-working regex (does not work for special symbols % or $)
public System.Tuple<string, string> GetParts(string str, string beginMark, string endMark)
{
var pattern =
new Regex(beginMark + #"(?<val>.*?)" + endMark,
RegexOptions.Compiled |
RegexOptions.Singleline);
return (from Match match in pattern.Matches(str)
where match.Success
select new Tuple(
match.Value,
match.Groups["val"].Value))
.ToList();
}
Calling method:
string input = #"%sometext%\another text";
string replacedValue = "AAA";
var occurrences = GetPart(input, #"(%", ")");
foreach (var occurrence in occurrences)
{
Console.WriteLine(occurrence.Item1 + Environment.NewLine);
Console.WriteLine(occurrence.Item2 + Environment.NewLine);
// replace
onsole.WriteLine(input.Replace(occurrence.Item1, replacedValue) + Environment.NewLine);
}
Expected Output:
%sometext%
sometext
AAA\another text
You need to escape your symbols. Try to change
new Regex(beginMark + #"(?<val>.*?)" + endMark,
to
new Regex(Regex.Escape(beginMark) + #"(?<val>.*?)" + Regex.Escape(endMark),
I am trying to write a function that as input takes a string containing words and removes all single character words and returns the new string without the removed characters
E.g.:
string news = FunctionName("This is a test");
//'news' here should be "This is test".
Can you please help?
Obligatory LINQ one-liner:
string.Join(" ", "This is a test".Split(' ').Where(x => x.Length != 1).ToArray())
Or as a nicer extension method:
void Main()
{
var output = "This is a test".WithoutSingleCharacterWords();
}
public static class StringExtensions
{
public static string WithoutSingleCharacterWords(this string input)
{
var longerWords = input.Split(' ').Where(x => x.Length != 1).ToArray();
return string.Join(" ", longerWords);
}
}
I'm sure there's a nicer answer using regex, but you could do the following:
string[] words = news.Split(' ');
StringBuilder builder = new StringBuilder();
foreach (string word in words)
{
if (word.Length > 1)
{
if (builder.ToString().Length ==0)
{
builder.Append(word);
}
else
{
builder.Append(" " + word);
}
}
}
string result = builder.ToString();
The interesting thing about this question is that presumably you also want to remove one of the spaces surrounding the single-letter word.
string[] oldText = {"This is a test", "a test", "test a"};
foreach (string s in oldText) {
string newText = Regex.Replace(s, #"\s\w\b|\b\w\s", string.Empty);
WL("'" + s + "' --> '" + newText + "'");
}
Output...
'This is a test' --> 'This is test'
'a test' --> 'test'
'test a' --> 'test'
With Linq syntax, you could do something like
return string.Join(' ', from string word in input.Split(' ') where word.Length > 1))
string str = "This is a test.";
var result = str.Split(' ').Where(s => s.Length > 1).Aggregate((s, next) => s + " " + next);
UPD
Using the extension method:
public static string RemoveSingleChars(this string str)
{
return str.Split(' ').Where(s => s.Length > 1).Aggregate((s, next) => s + " " + next);
}
//----------Usage----------//
var str = "This is a test.";
var result = str.RemoveSingleChars();