This question already has answers here:
Regex to match a word with + (plus) signs
(5 answers)
Search and replace method using regular expressions
(1 answer)
Closed 3 months ago.
Created an extension method and it works for normal words but When I added an # as part of search keyword it stopped working. Can someone help?
public static class Extensions
{
public static string ReplaceWholeWord(this string inputString, string oldValue, string newValue)
{
string pattern = #"\b#test\b"; // #"\b$\b".Replace("$",oldValue);
return Regex.Replace(inputString, pattern, newValue);
}
}
static void Main(string[] args)
{
string input = "#test, and #test but not testing. But yes to #test";
input = input.ReplaceWholeWord("#test", "text");
Console.WriteLine(input);
}
Related
This question already has answers here:
How do I replace the *first instance* of a string in .NET?
(15 answers)
How do I replace word in string except first occurrence using c#
(3 answers)
Why .NET String is immutable? [duplicate]
(13 answers)
Closed 2 years ago.
Let's imagine we have this string:
string Transport = "car motorcycle motorcycle plane train";
How can I find the first occurence of the word "motorcycle" in this string and change it in the original string to something else instead of having to create a separate string using LINQ?
string Transport = "car motorcycle motorcycle plane train";
string word = "motorcycle";
string pattern = Regex.Escape(word);
var regex = new Regex(pattern);
string result = regex.Replace(Transport, "something", 1);
Console.WriteLine(result);
This should do the trick. oldValue is the value you want to find and replace, newValue is the value you want to replace with.
static void Main(string[] args)
{
string transport = "car motorcycle motorcycle plane train";
transport = ReplaceFirst(transport, "motorcycle", "not motorcycle");
Console.WriteLine(transport);
// prints "car not motorcycle motorcylce plane train
}
static string ReplaceFirst(string values, string oldValue, string newValue)
{
int index = values.IndexOf(oldValue);
if (index == -1) return values;
values = values.Substring(0, index)
+ newValue
+ values.Substring(index + oldValue.Length);
return values;
}
I'm reading this question to mean that you don't want to use LINQ.*
Objective: To get all the non-alphanumeric characters even though they are not contiguous.
Setup: I have a textbox on an ASP.Net page that calls a C# code behind method on TextChanged. This event handler runs the textbox input against a Regex pattern.
Problem: I cannot create the proper Regex pattern that extracts all the non-alphanumeric characters.
This is the string input: string titleString = #"%2##$%^&";
These are the C# Regex Patterns that I have tried:
string titlePattern = #"(\b[^A-Za-z0-9]+)"; results with ##$%^& (Note: if I use this input string %2#35%^&, then the above regex pattern will identify the # sign, and then the %^&), but never the leading % sign).
string titlePattern = #"(\A[^A-Za-z0-9]+)"; results with %
string titlePattern = #"(\b\W[^A-Za-z0-9]+)"; results with ##$%^&
Side Note: I am also running this in a MS Visual Studio Console Application with a foreach loop in an effort to get all invalid characters into a collection and I also test the input and pattern using the web site: http://regexstorm.net/tester
Use the replace method with your selection string.
EDIT: After a closer reading I see that you wanted the opposite string. Here's both.
using System;
using System.Text.RegularExpressions;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
string Source = #"H)*e/.?l\l{}*o ][W!~`##""or^-_=+ld!";
string Trash = #"[^a-zA-Z0-9]";
string InvertedTrash = #"[a-zA-Z0-9]";
Output(Source, Trash);
Console.WriteLine($"{System.Environment.NewLine}Opposite Day!{System.Environment.NewLine}");
Output(Source, InvertedTrash);
Console.ReadKey();
}
static string TakeOutTheTrash(string Source, string Trash)
{
return (new Regex(Trash)).Replace(Source, string.Empty);
}
static void Output(string Source, string Trash)
{
string Sanitized = TakeOutTheTrash(Source, Trash);
Console.WriteLine($"Started with: {Source}");
Console.WriteLine($"Ended with: {Sanitized}");
}
}
}
This question already has answers here:
Find text in string with C#
(17 answers)
Closed 3 years ago.
How do I find out if one of my strings occurs in the other in C#?
For example, there are 2 strings:
string 1= "The red umbrella";
string 2= "red";
How would I find out if string 2 appears in string 1 or not?
you can use String Contains I guess. pretty sure there is similar question have been asked before How can I check if a string exists in another string
example :
if (stringValue.Contains(anotherStringValue))
{
// Do Something //
}
You can do it like this:
public static bool CheckString(string str1, string str2)
{
if (str1.Contains(str2))
{
return true;
}
return false;
}
Call the function:
CheckString("The red umbrella", "red") => true
This question already has answers here:
Check that email address is valid for System.Net.Mail.MailAddress
(6 answers)
Best Regular Expression for Email Validation in C#
(6 answers)
Closed 5 years ago.
Currently I'm using this code:
public static bool IsEmailAddress(this string value)
{
try
{
new System.Net.Mail.MailAddress(value);
return true;
}
catch ()
{
return false;
}
}
Is there a way to do this without using exceptions?
You could use a regular expression.
private const string EmailRegularExpression = #"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$";
private static Regex EmailValidRegex = new Regex(CommonValues.EmailRegularExpression, RegexOptions.Compiled | RegexOptions.IgnoreCase)
public static bool IsEmailValid(string emailAddress)
{
return !string.IsNullOrWhiteSpace(emailAddress) && EmailValidRegex.IsMatch(emailAddress);
}
See also http://www.regular-expressions.info/email.html which is where I snagged the expression from.
This question already has answers here:
Split comma-separated values
(6 answers)
Closed 8 years ago.
I have a string which is in following format or comma separated format
s1 ,s2,s3,s4,and so on. I want to convert it into
s1
s2
s3
s4
..
..
..
I know how I can do this by using a loop but I want to do this by regex in c# and in java without using the loop can I achive this ???
Here is how you can do it in Java.
public class MainProg {
public static void main(String[] args) {
String s = "s1,s2,s3,s4";
String z = s.replaceAll(",", "\n");
System.out.println(z);
}
}
find : \s*,\s*
replace with : \n
String.Join(Environment.NewLine, myString.Split(','));