Is it Possible to Perform Addition in a Regex? - asp.net

Assuming the placeholder $2 is populated with an integer, is it possible to increment it by 1?:
var strReplace = #"$2";
Regex.Replace(strInput, #"((.)*?)", strReplace);

You can use a callback version of Regex.Replace with a MatchEvaluator, see examples at:
http://msdn.microsoft.com/en-us/library/cft8645c.aspx
http://www.dotnetperls.com/regex-replace
Here's an example (ideone):
using System;
using System.Text.RegularExpressions;
class Program
{
static string AddOne(string s)
{
return Regex.Replace(s, #"\d+", (match) =>
{
long num = 0;
long.TryParse(match.ToString(), out num);
return (num + 1).ToString();
});
}
static void Main()
{
Console.WriteLine(AddOne("hello 123!"));
Console.WriteLine(AddOne("bai bai 11"));
}
}
Output:
hello 124!
bai bai 12

In standard (CS theoretic) regular expressions, it is impossible with a regular expression.
However, Perl and such have extensions to Regular Expressions, which has implications for their behaviour, and I am not familiar enough with them to definitely say that the extended regexes will not do it, but I'm fairly sure that this behaviour is not possible with a regex.

It's not possible with a standard regular expression but you can if you write a custom MatchEvaluator.
string str = "Today I have answered 0 questions on StackOverlow.";
string pattern = #"\w*?(\d)";
var result = Regex.Replace(str, pattern,
m => (int.Parse(m.Groups[0].Value)+1).ToString() );
Console.WriteLine(result);
Today I have answered 1 questions on StackOverlow.

Related

How to split string in C#

I have a string and I want to get this sub string. [ 10:30 to 11:30 ] .
I don't how to do it.
strong text
string a = "This is my string at -10:30 to 11:30-";
You need to use IndexOf and LastIndexOf to get the first and the last dash.
var firstDash = a.IndexOf("-");
var lastDash = a.LastIndexOf("-");
var timePeriod = a.Substring(firstDash + 1, lastDash - 1);
That should be it. Play with +1 and -1 in case I missed where the reading starts for the substring method.
You might also want to check for the result of firstDash and lastDash. If the value for any of them is -1 then the target string or character was not found.
You can get your desired string using Regex. Try below code to do that.
Regex example: Regex Test Link
CODE:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string a = "This is my string at -10:30 to 11:30-";
string pat = #"[0-9]{2}:[0-9]{2}\sto\s[0-9]{2}:[0-9]{2}";
// Instantiate the regular expression object.
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
// Match the regular expression pattern against a text string.
Match m = r.Match(a);
if(m.Success){
Console.WriteLine(m.Value);
}
else
{
Console.WriteLine("Nothing");
}
}
}
Let me give you the simplest code. The regex is same as the above.
String result = Regex.Match(a, "[0-9]{2}:[0-9]{2}\s*to\s*[0-9]{2}:[0-9]{2}").ToString();

remove duplicates from collection

I want to get a list of all Locales that have a different language, where the ISO3 code is used to identify the language of a Locale. I thought the following should work
class ISO3LangComparator implements Comparator<Locale> {
int compare(Locale locale1, Locale locale2) {
locale1.ISO3Language <=> locale2.ISO3Language
}
}
def allLocales = Locale.getAvailableLocales().toList()
def uniqueLocales = allLocales.unique {new ISO3LangComparator()}
// Test how many locales there are with iso3 code 'ara'
def arabicLocaleCount = uniqueLocales.findAll {it.ISO3Language == 'ara'}.size()
// This assertion fails
assert arabicLocaleCount <= 1
You are using the wrong syntax: you are using Collection.unique(Closure closure):
allLocales.unique {new ISO3LangComparator()}
You should use Collection.unique(Comparator comparator)
allLocales.unique (new ISO3LangComparator())
So simply use () instead of {}, and your problem is solved.
what Adam said.
or...
allLocales.unique{it.ISO3Language}
and you forget about the comparator

C# alternative for javascript escape function

what is an alternative for javascript escape function in c# for e.g suppose a string:"Hi Foster's i'm missing /you" will give "Hi%20Foster%27s%20i%27m%20missing%20/you" if we use javascript escape function, but what is the alternative for c#. i have searched for it but no use.
You can use:
string encoded = HttpUtility.JavaScriptStringEncode(str);
Note: You need at least ASP.NET 4.0 to run the above code.
var unescapedString = Microsoft.JScript.GlobalObject.unescape(yourEscapedString);
var escapedString = Microsoft.JScript.GlobalObject.escape(yourUnescapedString);
The best solution I've seen is mentioned on this blog - C#: Equivalent of JavaScript escape function by Kaushik Chakraborti. There is more to escaping javascript than simply url-encoding or replacing spaces with entities.
Following is the escape function implementation that you will find in Microsoft.JScript.dll...
[NotRecommended("escape"), JSFunction(JSFunctionAttributeEnum.None, JSBuiltin.Global_escape)]
public static string escape(string str)
{
string str2 = "0123456789ABCDEF";
int length = str.Length;
StringBuilder builder = new StringBuilder(length * 2);
int num3 = -1;
while (++num3 < length)
{
char ch = str[num3];
int num2 = ch;
if ((((0x41 > num2) || (num2 > 90)) &&
((0x61 > num2) || (num2 > 0x7a))) &&
((0x30 > num2) || (num2 > 0x39)))
{
switch (ch)
{
case '#':
case '*':
case '_':
case '+':
case '-':
case '.':
case '/':
goto Label_0125;
}
builder.Append('%');
if (num2 < 0x100)
{
builder.Append(str2[num2 / 0x10]);
ch = str2[num2 % 0x10];
}
else
{
builder.Append('u');
builder.Append(str2[(num2 >> 12) % 0x10]);
builder.Append(str2[(num2 >> 8) % 0x10]);
builder.Append(str2[(num2 >> 4) % 0x10]);
ch = str2[num2 % 0x10];
}
}
Label_0125:
builder.Append(ch);
}
return builder.ToString();
}
Code taken from Reflector.
The best solution I've seen is mentioned on this blog - C#: Equivalent of JavaScript escape function by Kaushik Chakraborti. There is more to escaping javascript than simply url-encoding or replacing spaces with entities.
I noticed another solution in the comments in KodeSharp article that may be better. The comment says it is more compatible with UTF-8 and does not require the reference to JScript. Is this better?
(Dependent on System.Web.Extensions.dll)
using System.Web.Script.Serialization;
JavaScriptSerializer serialiser = new JavaScriptSerializer();
serialiser.Serialize("some \"string\"")
string myString = "Hello my friend";
myString = myString.Replace(" ", "%20");
This would replace all " " with "%20".
Is this what you wanted?
You can try this
Uri.EscapeDataString(Obj);

Function to convert "camel case" type text to text with spaces in between? ie: HelloWorld --> Hello World

Anyone know of a nice efficient function that could convert, for example:
HelloWorld --> Hello World
helloWorld --> Hello World
Hello_World --> Hello World
hello_World --> Hello World
It would be nice to be able to handle all these situations.
Preferably in in VB.Net, or C#.
I donĀ“t know if this is the most efficient way. But this method works fine:
EDIT 1: I have include Char.IsUpper suggestion in the comments
EDIT 2: included another suggestion in the comments: ToCharArray is superfluous because string implements enumerable ops as a char too, i.e. foreach (char character in input)
EDIT 3: I've used StringBuilder, like #Dan commented.
public string CamelCaseToTextWithSpaces(string input)
{
StringBuilder output = new StringBuilder();
input = input.Replace("_", "");
foreach (char character in input)
{
if (char.IsUpper(character))
{
output.Append(' ');
}
if (output.Length == 0)
{
// The first letter must be always UpperCase
output.Append(Char.ToUpper(character));
}
else
{
output.Append(character);
}
}
return output.ToString().Trim();
}
There are some other possibilities you might want to cater for - for instance, you probably don't want to add spaces to abbreviations/acronyms.
I'd recommend using:
Private CamelCaseConverter As Regex = New Regex("(?<char1>[0-9a-z])(?<char2>[A-Z])", RegexOptions.Compiled + RegexOptions.CultureInvariant)
Public Function CamelCaseToWords(CamelCaseString As String) As String
Return CamelCaseConverter.Replace(CamelCaseString, "${char1} ${char2}")
End Function
'Gives:
'CamelCase => Camel Case
'PIN => PIN
What it doesn't do is uppercase the first letter of the first word, but you can look at the other examples for ways of doing that, or maybe someone can come up with a clever RegEx way of doing it.
Sounded fun so I coded it the most important part is the regex take a look at this site for more documentation.
private static string BreakUpCamelCase(string s)
{
MatchCollection MC = Regex.Matches(s, #"[0-9a-z][A-Z]");
int LastMatch = 0;
System.Text.StringBuilder SB = new StringBuilder();
foreach (Match M in MC)
{
SB.AppendFormat("{0} ", s.Substring(LastMatch, M.Index + 1 - LastMatch));
LastMatch = M.Index + 1;
}
if (LastMatch < s.Length)
{
SB.AppendFormat("{0} ", s.Substring(LastMatch));
}
return SB.ToString();
}

Formatting JSON in ASP.NET HttpResponse

I'm sending back a bunch of image tags via JSON in my .ashx response.
I am not sure how to format this so that the string comes back with real tags. I tried to HtmlEncode and that sort of fixed it but then I ended up with this stupid \u003c crap:
["\u003cimg src=\"http://www.sss.com/image/65.jpg\" alt=\"\"\u003e\u003c/li\u003e","\u003cimg src=\"http://www.xxx.com/image/61.jpg\" alt=\"\"\u003e\u003c/li\u003e"]
What the heck is \u003c ?
here's my code that created the JSON for response to my .ashx:
private void GetProductsJSON(HttpContext context)
{
context.Response.ContentType = "text/plain";
int i = 1;
...do some more stuff
foreach(Product p in products)
{
string imageTag = string.Format(#"<img src=""{0}"" alt=""""></li>", WebUtil.ImageUrl(p.Image, false));
images.Add(imageTag);
i++;
}
string jsonString = images.ToJSON();
context.Response.Write(HttpUtility.HtmlEncode(jsonString));
}
the toJSON is simply using the helper method outlined here:
http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx
\u003c is an escaped less-than character in unicode (Unicode character 0x003C).
The AJAX response is fine. When that string is written to the DOM, it will show up as a normal "<" character.
You are returning JSON array. Once parsed using eval("("+returnValue+")") it is in readily usable condition.
EDIT: This code is from jquery.json.js file:
var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
var meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
$.quoteString = function(string)
// Places quotes around a string, inteligently.
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
{
if (escapeable.test(string))
{
return '"' + string.replace(escapeable, function (a)
{
var c = meta[a];
if (typeof c === 'string') {
return c;
}
c = a.charCodeAt();
return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
}) + '"';
}
return '"' + string + '"';
};
Hope this gives you some direction to go ahead.
all you need to do is to use javascript eval function to get a pure HTML (XML) markup on the front end.
i.e. in a ajax call to a webservice, this can be the success handler of tha call,
the service returns a complex html element:
...
success: function(msg) {$(divToBeWorkedOn).html(**eval(**msg**)**);alert(eval(msg));},
...

Resources