I just came across the following post Replace emoticon with word in tweet using regex c# where smileys are parsed and replaced with some custom text:
static string ReplaceSmile(Match m) {
string x = m.ToString();
if (x.Equals(":)")) {
return "happy";
} else if (x.Equals(":(")) {
return "sad";
}
return x;
}
static void Main() {
string text = "Today is a sunny day :). But tomorrow it is going to rain :(";
Regex rx = new Regex(#":[()]");
string result = rx.Replace(text, new MatchEvaluator(ReplaceSmile));
System.Console.WriteLine("result=[" + result + "]");
}
Can you help me to achieve the same via JavaScript say I have smileys in a string in JavaScript variable, how to achieve the same behavior what we did in C#?
var result = "hello :)".replace(/:[()]/, "replacement");
See the JavaScript string replacement method for more details.
In your case I probably wouldn't use regular expressions. I would just do this -
var text = "Today is a sunny day :). But tomorrow it is going to rain :(";
text = text.replace(":)", "happy");
text = text.replace(":(", "sad");
// text is "Today is a sunny day happy. But tomorrow it is going to rain sad"
You can use "replace" method's overload:
var text = "hello :) :(";
var pattern = /:[()]/ig;
text = text.replace(pattern, function (match, p) {
if (match == ':)') {
return "happy";
}
else if (match == ':(') {
return "sad";
} else {
return match;
}
});
console.log(text);
Demo: http://jsfiddle.net/JDx53/1/
Something like this if you don't care to use regex:
var happy_replacement = "smile!";
var sad_replacement = "frown...";
var happy_replaced = ":) Sunshine and lollipops".replace(":)",happy_replacement);
var sad_replaced = ":( Snips and snails".replace(":(",sad_replacement);
var both_replaced =
":( and :)"
.replace(":(",sad_replacement)
.replace(":)",happy_replacement);
Edit: A function to do them both.
function replace_all(raw) {
var happy_replacement = "smile!";
var sad_replacement = "frown...";
var replaced =
input
.replace(":(",sad_replacement)
.replace(":)",happy_replacement);
return replaced;
}
var output = replace_all(":) and :(");
Related
I have created a regex function and called it when the data is being saved.
public static bool CheckSpecialCharacter(string value)
{
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(#"[~`!##$%^*()=|\{}';.,<>]");
if (regex.IsMatch(value))
{
return false;
}
else
{
return true;
}
}
Used here:
if (ClassName.CheckSpecialCharacter(txt_ExpName1.Text)==false)
{
lblErrMsg.Text = "Special characters not allowed";
return;
}
Now instead of writing "Special characters not allowed", I want to attach the 1st special character that was entered in the textbox, so
if # was entered, the message should be read as "Special character # not allowed"
Is it possible to do this? please help.Thanks.
Try following code.
public static string CheckSpecialCharacter(string value)
{
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(#"[~`!##$%^*()=|\{}';.,<>]");
var match = regex.Match(value);
if (match.Success)
{
return match.Value;
}
else
{
return string.empty;
}
}
usage:
var value = ClassName.CheckSpecialCharacter(txt_ExpName1.Text);
if (!string.IsNullOrEmpty(value ))
{
lblErrMsg.Text = value + " Special characters not allowed";
return;
}
OR you can do it by returning bool and adding one out parameter in the function, but i will not suggest that.. check this link
EDIT - To do the same thing in Javascript
function CheckSpecialCharacter(value)
{
var res = value.match(/[~`!##$%^*()=|\{}';.,<>]/g);
return res == null ? "" : res[0];
}
usage:
var value = CheckSpecialCharacter(document.getElementById("txt_ExpName1").value);
if(value != "")
{
document.getElementById("lblErrMsg").innerHTML = value + " Special characters not allowed";
}
Try this:
public static bool CheckSpecialCharacter(string value, out string character)
{
var regex = new System.Text.RegularExpressions.Regex(#"[~`!##$%^*()=|\{}';.,<>]");
var match = regex.Match(value);
character = regex.Match(value).Value;
return match.Length == 0;
}
and then
string character;
if (ClassName.CheckSpecialCharacter(txt_ExpName1.Text, out character) == false)
{
lblErrMsg.Text = character + " Special characters not allowed";
return;
}
You can just use the Matches(string) function from Regex to get the matches then check the first element like this :
var regex = new Regex(#"[~`!##$%^*()=|\{}';.,<>]");
var matches = regex.Matches("This contains # two b#d characters");
if (matches.Count > 0)
{
var firstBadCharacter = matches[0];
}
Then you can wrap the result of your check in an Exception :
throw new ArgumentException("Special character '" + firstBadCharacter + "' not allowed.");
I want to split the below string with given output.
Can anybody help me to do this.
Examples:
/TEST/TEST123
Output: /Test/
/TEST1/Test/Test/Test/
Output: /Test1/
/Text/12121/1212/
Output: /Text/
/121212121/asdfasdf/
Output: /121212121/
12345
Output: 12345
I have tried string.split function but it is not worked well. Is there any idea or logic that i can implement to achieve this situation.
If the answer in regular expression that would be fine for me.
You simply want the first result of Spiting by /
string output = input.Split('/')[0];
But in case that you have //TEST/ and output should be /TEST you can use regex.
string output = Regex.Matches(input, #"\/?(.+?)\/")[0].Groups[1].Value;
For your 5th case : you have to separate the logic. for example:
public static string Method(string input)
{
var split = input.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
if (split.Length == 0) return input;
return split[0];
}
Or using regex.
public static string Method(string input)
{
var matches = Regex.Matches(input, #"\/?(.+?)\/");
if (matches.Count == 0) return input;
return matches[0].Groups[1].Value;
}
Some results using method:
TEST/54/ => TEST
TEST => TEST
/TEST/ => TEST
I think this would work:
string s1 = "/TEST/TEST123";
string s2 = "/TEST1/Test/Test/Test/";
string s3 = "/Text/12121/1212/";
string s4 = "/121212121/asdfasdf/";
string s5 = "12345";
string pattern = #"\/?[a-zA-Z0-9]+\/?";
Console.WriteLine(Regex.Matches(s1, pattern)[0]);
Console.WriteLine(Regex.Matches(s2, pattern)[0]);
Console.WriteLine(Regex.Matches(s3, pattern)[0]);
Console.WriteLine(Regex.Matches(s4, pattern)[0]);
Console.WriteLine(Regex.Matches(s5, pattern)[0]);
class Program
{
static void Main(string[] args)
{
string example = "/TEST/TEST123";
var result = GetFirstItem(example);
Console.WriteLine("First in the list : {0}", result);
}
static string GetFirstItem(string value)
{
var collection = value?.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var result = collection[0];
return result;
}
}
StringSplitOptions.RemoveEmptyEntries is an enum which tells the Split function that when it has split the string into an array, if there are elements in the array that are empty strings, the function should not include the empty elements in the results. Basically you want the collection to contain only values.
public string functionName(string input)
{
if(input.Contains('/'))
{
string SplitStr = input.Split('/')[1];
return "/"+SplitStr .Substring(0, 1) +SplitStr.Substring(1).ToLower()+"/"
}
return input;
}
output = (output.Contains("/"))? '/' +input.Split('/')[1]+'/':input;
private void button1_Click(object sender, EventArgs e)
{
string test = #"/Text/12121/1212/";
int first = test.IndexOf("/");
int last = test.Substring(first+1).IndexOf("/");
string finall = test.Substring(first, last+2);
}
i try this code with all your examples and get correct output. try this.
The following method may help you.
public string getValue(string st)
{
if (st.IndexOf('/') == -1)
return st;
return "/" + st.Split('/')[1] + "/";
}
I'm having a string with <link rid="bib*">222</link> and <link rid="fig1">333</link>
now i want to replace all the occurance of the above text with rid="bib*", with <CITATION id="CD1">222</CITATION> and replace all the occurance of the text with rid="fig*" , with <FigRef id="fig*">222</FigRef>.
i tried something like this
var reg = new Regex(#"\<link rid=""bib(?<myText>.+?)""\>(?<myText2>.+?)\</link\>$");
but i dont know how to proceed with this and got stuck.
Please help me with this.
Here is a solution based a very similar regex:
private const string REGEX_LINK = #"<link\s+rid=""([^""\d]+)(\d+)"">(.*?)</link>";
private const int REGEX_LINK_GRP_RID_NAME = 1;
private const int REGEX_LINK_GRP_RID_ID = 2;
private const int REGEX_LINK_GRP_VALUE = 3;
static void Main(string[] args)
{
var testInputString = "I'm having a string with <link rid=\"bib123\">222</link> and <link rid=\"fig456\">333</link> now i want to replace all the occurances...";
Regex linkFinder = new Regex(REGEX_LINK, RegexOptions.IgnoreCase);
var result = linkFinder.Replace(testInputString, new MatchEvaluator(LinkMatchEvaluator));
Console.WriteLine(result);
Console.ReadKey();
}
private static string LinkMatchEvaluator(Match m)
{
const string CITATION_RID_NAME = "bib";
const string FIGREF_RID_NAME = "fig";
var ridName = m.Groups[REGEX_LINK_GRP_RID_NAME].Value.ToLower();
var ridID = m.Groups[REGEX_LINK_GRP_RID_ID].Value;
var value = m.Groups[REGEX_LINK_GRP_VALUE].Value;
if (ridName == CITATION_RID_NAME)
{
return String.Format("<CITATION id=\"CD{0}\">{1}</CITATION>", ridID, value);
}
else if (ridName == FIGREF_RID_NAME)
{
return String.Format("<FigRef id=\"fig{0}\">{1}</FigRef>", ridID, value);
}
return m.Value;
}
Thanks for your reply guys. Finally i found the solution for my own question.Now i got the solution for the problem i had. I solved it like this.
public enum intLinks
{
bib = 1,
fig = 2,
tab=3,
tb=4
}
This is the method to replace the content with the matching pattern.
public string NumberedReplaceTest(string input, intLinks refToFind)
{
//"<link rid=\"bib1\">1</link>"
Regex regex = new Regex(#"<link rid=""" + refToFind.ToString() + #"(?<sequence>\d*)"">(\r?\n)*(?<number>[a-zA-Z0-9]*)(\r?\n)*</link>");
if (!regex.IsMatch(input))
return input;
switch (refToFind)
{
case intLinks.bib: return regex.Replace(input, "<Citation CID=\"CR${sequence}\">${number}</Citation>");
case intLinks.fig: return regex.Replace(input, "<InternalRef RefID=\"Fig${sequence}\">${number}</InternalRef>");
case intLinks.tab: return regex.Replace(input, "<InternalRef RefID=\"Tab${sequence}\">${number}</InternalRef>");
case intLinks.tb: return regex.Replace(input, "<InternalRef RefID=\"Tab${sequence}\">${number}</InternalRef>");
default: return input;
}
}
I'm calling the method like this.
bodyString = NumberedReplaceTest(bodyString,intLinks.bib);
bodyString = NumberedReplaceTest(bodyString, intLinks.fig);
bodyString = NumberedReplaceTest(bodyString, intLinks.tab);
bodyString = NumberedReplaceTest(bodyString, intLinks.tb);`
C# or VB.NET suggestion are welcome.
I have the following code:
Dim someText = "Stack Over Flow Community"
Dim someWord = "Over Community"
If someText.Contains(someWord) Then
Response.Write("Word found.")
Else
Response.Write("No word found.")
End If
Function Contains looks only for next words from left to right.
someText.Contains("Over Stack") returns False
someText.Contains("Stack Community") returns False
I want all of these to return True as long as there are words that exist in the string.
Is there any existing function that cover any case regardless of words position in the string?
words.Split(' ').Any(someText.Contains)
someText.Split(' ').Intersect(someWord.Split(' ')).Any();
public static class StringExtension
{
public static bool ContainsWord(this string source, string contain)
{
List<string> sourceList = source.Split(' ').ToList();
List<string> containList = contain.Split(' ').ToList();
return sourceList.Intersect(containList).Any();
}
}
string someText = "Stack Over Flow Community";
var res = someText.ContainsWord("Over Stack"); // return true
var res1 = someText.ContainsWord("Stack Community"); // return true
var res2 = someText.ContainsWord("Stack1 Community"); // return false
An alternative to the Linq solutions would be an extension method:
public static bool ContainsAllWords(this string input, string search)
{
foreach (string word in search.split(' ', StringSplitOptions.RemoveEmptyEntries))
{
if (!input.Contains(word))
return false;
}
return true;
}
Usage:
string test = "stack overflow";
string searchPhrase = "overflow stack";
Console.WriteLine(test.ContainsAllWords(searchPhrase));
Better for re-usability and makes your code more declarative (imho).
Does anyone have any good c# code (and regular expressions) that will parse a string and "linkify" any urls that may be in the string?
It's a pretty simple task you can acheive it with Regex and a ready-to-go regular expression from:
http://regexlib.com/
Something like:
var html = Regex.Replace(html, #"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+" +
"\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?" +
"([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$",
"$1");
You may also be interested not only in creating links but in shortening URLs. Here is a good article on this subject:
Resolve and shorten URLs in C#
See also:
Regular Expression Workbench at MSDN
Converting a URL into a Link in C# Using Regular Expressions
Regex to find URL within text and make them as link
Regex.Replace Method at MSDN
The Problem With URLs by Jeff Atwood
Parsing URLs with Regular Expressions and the Regex Object
Format URLs in string to HTML Links in C#
Automatically hyperlink URL and Email in ASP.NET Pages with C#
well, after a lot of research on this, and several attempts to fix times when
people enter in http://www.sitename.com and www.sitename.com in the same post
fixes to parenthisis like (http://www.sitename.com) and http://msdn.microsoft.com/en-us/library/aa752574(vs.85).aspx
long urls like: http://www.amazon.com/gp/product/b000ads62g/ref=s9_simz_gw_s3_p74_t1?pf_rd_m=atvpdkikx0der&pf_rd_s=center-2&pf_rd_r=04eezfszazqzs8xfm9yd&pf_rd_t=101&pf_rd_p=470938631&pf_rd_i=507846
we are now using this HtmlHelper extension... thought I would share and get any comments:
private static Regex regExHttpLinks = new Regex(#"(?<=\()\b(https?://|www\.)[-A-Za-z0-9+&##/%?=~_()|!:,.;]*[-A-Za-z0-9+&##/%=~_()|](?=\))|(?<=(?<wrap>[=~|_#]))\b(https?://|www\.)[-A-Za-z0-9+&##/%?=~_()|!:,.;]*[-A-Za-z0-9+&##/%=~_()|](?=\k<wrap>)|\b(https?://|www\.)[-A-Za-z0-9+&##/%?=~_()|!:,.;]*[-A-Za-z0-9+&##/%=~_()|]", RegexOptions.Compiled | RegexOptions.IgnoreCase);
public static string Format(this HtmlHelper htmlHelper, string html)
{
if (string.IsNullOrEmpty(html))
{
return html;
}
html = htmlHelper.Encode(html);
html = html.Replace(Environment.NewLine, "<br />");
// replace periods on numeric values that appear to be valid domain names
var periodReplacement = "[[[replace:period]]]";
html = Regex.Replace(html, #"(?<=\d)\.(?=\d)", periodReplacement);
// create links for matches
var linkMatches = regExHttpLinks.Matches(html);
for (int i = 0; i < linkMatches.Count; i++)
{
var temp = linkMatches[i].ToString();
if (!temp.Contains("://"))
{
temp = "http://" + temp;
}
html = html.Replace(linkMatches[i].ToString(), String.Format("{1}", temp.Replace(".", periodReplacement).ToLower(), linkMatches[i].ToString().Replace(".", periodReplacement)));
}
// Clear out period replacement
html = html.Replace(periodReplacement, ".");
return html;
}
protected string Linkify( string SearchText ) {
// this will find links like:
// http://www.mysite.com
// as well as any links with other characters directly in front of it like:
// href="http://www.mysite.com"
// you can then use your own logic to determine which links to linkify
Regex regx = new Regex( #"\b(((\S+)?)(#|mailto\:|(news|(ht|f)tp(s?))\://)\S+)\b", RegexOptions.IgnoreCase );
SearchText = SearchText.Replace( " ", " " );
MatchCollection matches = regx.Matches( SearchText );
foreach ( Match match in matches ) {
if ( match.Value.StartsWith( "http" ) ) { // if it starts with anything else then dont linkify -- may already be linked!
SearchText = SearchText.Replace( match.Value, "<a href='" + match.Value + "'>" + match.Value + "</a>" );
}
}
return SearchText;
}
It's not that easy as you can read in this blog post by Jeff Atwood. It's especially hard to detect where an URL ends.
For example, is the trailing parenthesis part of the URL or not:
http​://en.wikipedia.org/wiki/PCTools(CentralPointSoftware)
an URL in parentheses (http​://en.wikipedia.org) more text
In the first case, the parentheses are part of the URL. In the second case they are not!
Have found following regular expression
http://daringfireball.net/2010/07/improved_regex_for_matching_urls
for me looks very good. Jeff Atwood solution doesn't handle many cases. josefresno seem to me handle all cases. But when I have tried to understand it (in case of any support requests) my brain was boiled.
There is class:
public class TextLink
{
#region Properties
public const string BeginPattern = "((http|https)://)?(www.)?";
public const string MiddlePattern = #"([a-z0-9\-]*\.)+[a-z]+(:[0-9]+)?";
public const string EndPattern = #"(/\S*)?";
public static string Pattern { get { return BeginPattern + MiddlePattern + EndPattern; } }
public static string ExactPattern { get { return string.Format("^{0}$", Pattern); } }
public string OriginalInput { get; private set; }
public bool Valid { get; private set; }
private bool _isHttps;
private string _readyLink;
#endregion
#region Constructor
public TextLink(string input)
{
this.OriginalInput = input;
var text = Regex.Replace(input, #"(^\s)|(\s$)", "", RegexOptions.IgnoreCase);
Valid = Regex.IsMatch(text, ExactPattern);
if (Valid)
{
_isHttps = Regex.IsMatch(text, "^https:", RegexOptions.IgnoreCase);
// clear begin:
_readyLink = Regex.Replace(text, BeginPattern, "", RegexOptions.IgnoreCase);
// HTTPS
if (_isHttps)
{
_readyLink = "https://www." + _readyLink;
}
// Default
else
{
_readyLink = "http://www." + _readyLink;
}
}
}
#endregion
#region Methods
public override string ToString()
{
return _readyLink;
}
#endregion
}
Use it in this method:
public static string ReplaceUrls(string input)
{
var result = Regex.Replace(input.ToSafeString(), TextLink.Pattern, match =>
{
var textLink = new TextLink(match.Value);
return textLink.Valid ?
string.Format("{1}", textLink, textLink.OriginalInput) :
textLink.OriginalInput;
});
return result;
}
Test cases:
[TestMethod]
public void RegexUtil_TextLink_Parsing()
{
Assert.IsTrue(new TextLink("smthing.com").Valid);
Assert.IsTrue(new TextLink("www.smthing.com/").Valid);
Assert.IsTrue(new TextLink("http://smthing.com").Valid);
Assert.IsTrue(new TextLink("http://www.smthing.com").Valid);
Assert.IsTrue(new TextLink("http://www.smthing.com/").Valid);
Assert.IsTrue(new TextLink("http://www.smthing.com/publisher").Valid);
// port
Assert.IsTrue(new TextLink("http://www.smthing.com:80").Valid);
Assert.IsTrue(new TextLink("http://www.smthing.com:80/").Valid);
// https
Assert.IsTrue(new TextLink("https://smthing.com").Valid);
Assert.IsFalse(new TextLink("").Valid);
Assert.IsFalse(new TextLink("smthing.com.").Valid);
Assert.IsFalse(new TextLink("smthing.com-").Valid);
}
[TestMethod]
public void RegexUtil_TextLink_ToString()
{
// default
Assert.AreEqual("http://www.smthing.com", new TextLink("smthing.com").ToString());
Assert.AreEqual("http://www.smthing.com", new TextLink("http://www.smthing.com").ToString());
Assert.AreEqual("http://www.smthing.com/", new TextLink("smthing.com/").ToString());
Assert.AreEqual("https://www.smthing.com", new TextLink("https://www.smthing.com").ToString());
}
This works for me:
str = Regex.Replace(str,
#"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,#?^=%&:/~\+#]*[\w\-\#?^=%&/~\+#])?)",
"<a target='_blank' href='$1'>$1</a>");