Add space around each / using Humanizer or Regex - c#

I have a string like the following:
var text = #"Some text/othertext/ yet more text /last of the text";
I want to normalize the spaces around each slash so it matches the following:
var text = #"Some text / othertext / yet more text / last of the text";
That is, one space before each slash and one space after. How can I do this using Humanizer or, barring that, with a single regex? Humanizer is the preferred solution.
I'm able to do this with the following pair of regexes:
var regexLeft = new Regex(#"\S/"); // \S matches non-whitespace
var regexRight = new Regex(#"/\S");
var newVal = regexLeft.Replace(text, m => m.Value[0] + " /");
newVal = regexRight.Replace(newVal, m => "/ " + m.Value[1]);

Are you looking for this:
var text = #"Some text/othertext/ yet more text /last of the text";
// Some text / othertext / yet more text / last of the text
string result = Regex.Replace(text, #"\s*/\s*", " / ");
slash surrounded by zero or more spaces replaced by slash surrounded by exactly one space.

Related

C# - how can i convert “text text 542050.0000 text text” to “text text 542050 text text”?

How can I convert the following string:
string x = "text text 542050.0000 text 245.00 text";
to this: "text text 542050 text 245 text"
i want to keep all text in this string , just remove decimal part of numbers
If you want to solve for the general case of removing decimals in strings, you can use RegEx:
var input = "text text 542050.0000 text text";
var regex = "((?<keep>[0-9]+)\\.[0-9]+)";
var matchEvaluator = new System.Text.RegularExpressions.MatchEvaluator((m) => m.Groups["keep"].Value);
var output = System.Text.RegularExpressions.Regex.Replace(input, regex, matchEvaluator);
The RegEx will match all decimals, and return the whole part as a replacement. Note that if you have a string like 5.2.1 then this will result in "5.1".
If you want to output a specific number of decimal places you could try this:
var input = "text text 542050.0129 text text";
var regex = "([0-9]+\\.[0-9]+)";
var matchEvaluator = new System.Text.RegularExpressions.MatchEvaluator((m) => {
var decimalValue = double.Parse(m.Groups[0].Value);
return String.Format("{0:0.000}", Math.Round(decimalValue, 3));
});
var output = System.Text.RegularExpressions.Regex.Replace(input, regex, matchEvaluator);
In my example, I've rounded to 3 dp and formatted with 3 dp (formatting to ensure that it always outputs .000 - you can remove this step if you don't need it). For "542050.0129" above, it would output "542050.013"

Regex for text between two characters

I'm trying to get some text between two strings in C# in regex expression.
The text is in variable (tb1.product_name) : Example Text | a:10,Colour:Green
Get all text before |, in this case, Example Text
Get all text between : and ,, in this case, 10
In two differents regex.
I try with:
Regex.Match(tb1.product_name, #"\:([^,]*)\)").Groups[1].Value
But this doesn't work.
If it is not so necessary to use regex, you can do this simply by using string.Substring & string.IndexOf:
string str = "Example Text | a:10,Colour:Green";
string strBeforeVerticalBar = str.Substring(0, str.IndexOf('|'));
string strInBetweenColonAndComma = str.Substring(str.IndexOf(':') + 1, str.IndexOf(',') - str.IndexOf(':') - 1);
Edit 1:
I feel Regex might be an overkill for something as simple as this. Also if use what i suggested, you can add Trim() at the end to remove whitespaces, if any. Like:
string strBeforeVerticalBar = str.Substring(0, str.IndexOf('|')).Trim();
string strInBetweenColonAndComma = str.Substring(str.IndexOf(':') + 1, str.IndexOf(',') - str.IndexOf(':') - 1).Trim();
string str = #"Example Text |a:10,Colour: Green";
Match match = Regex.Match(str, #"^([A-Za-z\s]*)|$");
Match match2= Regex.Match(str, #":([0-9]*),");
//output Example Text
Console.WriteLine(match.Groups[1].Value);
//output 10
Console.WriteLine(match2.Groups[1].Value);

Remove whitespace near a character using regex in a long text

How do I delete one or mores white spaces near a character in a long text. I do not want to remove other white spaces which are not present adjacent to the matching string. I only want to remove all white spaces next to the matching character and not all white spaces of the input string. For example:
[text][space][space]![space][text] should result in [text]![text]
[text][space][space]![space][space][space][text] should result in [text]![text]
[text][space]![space][space][text] should result in [text]![text]
[text][space]![space][text] should result in [text]![text]
[text]![space][space][text] should result in [text]![text]
[text][space][space]![text] should result in [text]![text]
[text][space][space]! should result in [text]!
![space][space][text] should result in ![text]
The code I am going to write is:
for (int i = 0 to length of string)
{
if (string[i] == character) //which is the desired character "!"
{
int location = i+1;
//remove all whitespace after the character till a non-whitespace character
//is found or string ends
while (string[location] == whitespace)
{
string[location].replace(" ", "");
location++;
}
int location = i-1;
//remove all whitespace before the character till a non-whitespace character
//is found or string ends
while (string[location] == whitespace)
{
string[location].replace(" ", "");
location--;
}
}
}
Is there a better way of removing whitespaces near a character using Regex?
UPDATE: I do not want to remove other white spaces which are not present adjacent to the matching string. For example:
some_text[space]some_other_text[space][space]![space]some_text[space]some_other_text
is
some_text[space]some_other_text!some_text[space]some_other_text
Regex rgx = new Regex(pattern);
string input = "This is text with far too much " +
"whitespace.";
string pattern = "\\s*!\\s*";
string replacement = "!";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
taken from http://msdn.microsoft.com/de-de/library/vstudio/xwewhkd1.aspx

Wrap text between two asterisks in HTML *bold*

What I want to do is take a string like the following
This is my string and *this text* should be wrapped with <strong></strong>
The result should be
This is my string and this text should be wrapped with
This seems to work pretty well:
var str = "This is my string and *this text* should be wrapped with";
var updatedstr = String.Concat(
Regex.Split(str, #"\*")
.Select((p, i) => i % 2 == 0 ? p :
string.Concat("<strong>", p, "</strong>"))
.ToArray()
);
What about this:
string s = "This is my string and *this text* should be wrapped with <strong></strong>";
int i = 0;
while (s.IndexOf('*') > -1)
{
string tag = i % 0 == 0 ? "<strong>" : "</strong>";
s = s.Substring(0, s.indexOf('*')) + tag + s.Substring(s.indexOf('*')+1);
++i;
}
Or Marty Wallace's regex idea in the comments on the question, \*[^*]+?\*
You can use a very simple regex for this case:
var text = "";
text = Regex.Replace(text, #"\*([^*]*)\*", "<b>$1</b>");
See the .NET regex demo. Here, \*([^*]*)\ matches
\* - a literal asterisk (* is a special regex metacharacter and needs escaping in the literal meaning)
([^*]*) - Group 1: zero or more chars other than a * char
\* - a * char.
The $1 in the replacement pattern refers to the value captured in Group 2.
Demo screen:

Find delimiters in a string and mark that position

I'm trying to figure out how to record the position of a delimiter in a string of text entered by the user.
So if the user entered text:
orange red green yellow?
* * * *
I would want to mark the space after each word along with the question mark. (Those stars should be lining up with the delimiters.)
I know how to search the string for a certain character or set of characters, but not how I would mark it to receive a star on the next line.
string input = "orange red green yellow?";
List<int> indexes = Regex.Matches(input, #"[^\w]+").Cast<Match>()
.Select(m => m.Index)
.ToList();
or if you want to replace delimeters with *
var output = Regex.Replace(input, #"[^\w]+","*");
EDIT
var output = String.Join("",input.Select(c => char.IsLetter(c)?" ":"*"));
text = text.Replace(" ", "? ");

Categories

Resources