I have a string like 30+20%. Now I want to replace 20% with (20/100). Thats it.
If the percent doesn't occur in any other situation in the string, you don't even need a regular expression:
s = s.Replace("%", "/100");
To add the parentheses you need the regular expression though:
s = Regex.Replace(s, #"(\d{1,3})%", "($1/100)");
string s="30+20%";
s=s.Replace("%","/100)");
s=s.Replace("+","+(");
I'll just assume you run Perl
input="30+20%"
echo $input | perl -pe 's#(\d+)%#\($1/100\)#g'
EDIT: just read the tags, anyways, the regex should work in C#
That should be an easy regex to try. 1 to 3 digits followed by a percentage sign.
You need to capture the 1-3 digits group for backreference, and use it to create
(DIGITS/100) string.
You can play here :http://gskinner.com/RegExr/ to learn regexes.
I'm not sure what programming language are you using but this is how you would do this in python:
import re
re.sub(r'(\d*)%', r'\1/100', '30+20%')
The returned string will be '30+20/100'.
Explanation:
Let's look at the regex. r'\d*%' is a regex that matches a series of digits followed by the % sign. I put paranthesis arount (\d*) to tell the regex compiler that the series of digits (aka the number) is the first group. The second arguemnt tells the sub functions how to replace the matched string. The argument '\1/100' tells the sub function I want it to replace the matched string with the value of the first group matched by the regex (through the \1 part) followed by /100.
You can check the python re module for more information.
Try this
string resultString = null;
try {
resultString = Regex.Replace(subjectString, #"\b(\d+)%", "($1/100)");
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
Related
I'm trying to find a regexp that only matches strings if they don't contain a dot, e.g. it matches stackoverflow, 42abc47 or a-bc-31_4 but doesn't match: .swp, stackoverflow or test..
^[^.]*$
or
^[^.]+$
Depending on whether you want to match empty string. Some applications may implicitly supply the ^ and $, in which case they'd be unnecessary. For example: the HTML5 input element's pattern attribute.
You can find a lot more great information on the regular-expressions.info site.
Use a regex that doesn't have any dots:
^[^.]*$
That is zero or more characters that are not dots in the whole string. Some regex libraries I have used in the past had ways of getting an exact match. In that case you don't need the ^ and $. Having a language in your question would help.
By the way, you don't have to use a regex. In java you could say:
!someString.contains(".");
Validation Require: First Character must be Letter and then Dot '.' is not allowed in Target String.
// The input string we are using
string input = "1A_aaA";
// The regular expression we use to match
Regex r1 = new Regex("^[A-Za-z][^.]*$"); //[\t\0x0020] tab and spaces.
// Match the input and write results
Match match = r1.Match(input);
if (match.Success)
{
Console.WriteLine("Valid: {0}", match.Value);
}
else
{
Console.WriteLine("Not Match");
}
I have a string something like JSON format:
XYZ DIV Parameters: width=\"1280\" height=\"720\", session=\"1\"
Now I want to remove width=\"1280\" height=\"720\" from this string.
Note: There can be any number in place of 1280 and 720. So, I can't just replace it with null.
Please tell me how to solve it? Either by Regex or any other better method possible.
Regex to be replaced with empty string:
(width|height)=\\"\d+\\"
Regex visualization:
Code:
string input = #"XYZ DIV Parameters: width=\""1280\"" height=\""720\"", session=\""1\""";
string output = Regex.Replace(input, #"(width|height)=\\""\d+\\""", string.Empty);
You could do a find and replace using the following regex:
width=\\"\d*+\\" replace with a blank string, as well as replacing height=\\"\d*+\\" with a blank string.
This is removing the entire text of width=\"XYZ\", if you wanted to just replace the numbers or blank out the numbers you can replace with a string that suits your needs (width=\"\" for example)
If you can guarantee the width and height will ALWAYS be in that format and ALWAYS follow each other seperated by a space, you can combine that into one bigger regex find/replace using width=\\"\d*+\\" height=\\"\d*+\\".
A little more explanation on the regex so you take something away, not just a quick fix :)
width=\\"\d*+\\" breaks down to:
width= pretty simple, just find the text you are looking for to start your removal.
\\" since \ is a special char in regex you have to escape it, then the " char can just follow it up like normal.
\d*+ digits \d, zero or more of them *, and then non greedy +. The important part here is the non greedy on the digits. If you left that off, your regex would look and consume digits until it found the last ". Not 100% needed in your case (since height is buffering) but it is still a lot safer.
\\" to end the regex out
This will do it:
string resultString = null;
try {
Regex regexObj = new Regex(#"^(.*?)width=\\"".*?\\"" height=\\"".*?\\""(.*?)$", RegexOptions.IgnoreCase);
resultString = regexObj.Replace(subjectString, #"$1width=\""\"" height=\""\""$2");
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
What I am trying to do is fairly simple, although I am running into difficulty. I have a string that is a url, it will have the format http://www.somedomain.com?id=someid what I want to retrive is the someid part. I figure I can use a regular expression but I'm not very good with them, this is what I tried:
Match match = Regex.Match(theString, #"*.?id=(/d.)");
I get a regex exception saying there was an error parsing the regex. The way I am reading this is "any number of characters" then the literal "?id=" followed "by any number of digits". I put the digits in a group so I could pull them out. I'm not sure what is wrong with this. If anyone could tell me what I'm doing wrong I would appreciated it, thanks!
No need for Regex. Just use built-in utilities.
string query = new Uri("http://www.somedomain.com?id=someid").Query;
var dict = HttpUtility.ParseQueryString(query);
var value = dict["id"]
You've got a couple of errors in your regex. Try this:
Match match = Regex.Match(theString, #".*\?id=(\d+)");
Specifically, I:
changed *. to .* (dot matches all non-newline chars and * means zero or more of the preceding)
added a an escape sequence before the ? because the question mark is a special charcter in regular expressions. It means zero or one of the preceding.
changed /d. to \d* (you had the slash going the wrong way and you used dot, which was explained above, instead of * which was also explained above)
Try
var match = RegEx.Match(theString, #".*\?id=(\d+)");
The error is probably due to preceding *. The * character in regex matches zero or more occurrences of previous character; so it cannot be the first character.
Probably a typo, but shortcut for digit is \d, not /d
. matches any character, you need to match one or more digits - so use a +
? is a special character, so it needs to be escaped.
So it becomes:
Match match = Regex.Match(theString, #".*\?id=(\d+)");
That being said, regex is not the best tool for this; use a proper query string parser or things will eventually become difficult to manage.
In C#, how would I capture the integer value in the URL like:
/someBlah/a/3434/b/232/999.aspx
I need to get the 999 value from the above url.
The url HAS to have the /someBlah/ in it.
All other values like a/3434/b/232/ can be any character/number.
Do I have escape for the '/' ?
Try the following
var match = Regex.Match(url,"^http://.*someblah.*\/(\w+).aspx$");
if ( match.Success ) {
string name = match.Groups[1].Value;
}
You didn't specify what names could appear in front of the ASPX file. I took the simple approach of using the \w regex character which matches letters and digits. You can modify it as necessary to include other items.
You are effectively getting the file name without an extension.
Although you specifically asked for a regular expression, unless you are in a scenario where you really need to use one, I'd recommend that you use System.IO.Path.GetFileNameWithoutExtension:
Path.GetFileNameWithoutExtension(Context.Request.FilePath)
^(?:.+/)*(?:.+)?/someBlah/(?:.+/)*(.+)\.aspx$
This is a bit exhaustive, but it can handle scenarios where /someBlah/ does not have to be at the beginning of the string.
The ?: operator implies a non-capturing group, which may or may not be supported by your RegEx flavor.
Regex regex = new Regex("^http://.*someBlah.*/(\\d+).aspx$");
Match match = regex.Match(url);
int result;
if (match.Success)
{
int.TryParse(match.Groups[1].Value, out result);
}
Using \d rather than \w ensures that you only match digits, and unless the ignore case flag is set the capitalisation of someBlah must be correct.
Given $displayHeight = "800";, replace whatever number is at 800 with int value y_res.
resultString = Regex.Replace(
im_cfg_contents,
#"\$displayHeight[\s]*=[\s]*""(.*)"";",
Convert.ToString(y_res));
In Python I'd use re.sub and it would work. In .NET it replaces the whole line, not the matched group.
What is a quick fix?
Building on a couple of the answers already posted. The Zero-width assertion allows you to do a regular expression match without placing those characters in the match. By placing the first part of the string in a group we've separated it from the digits that you want to be replaced. Then by using a zero-width lookbehind assertion in that group we allow the regular expression to proceed as normal but omit the characters in that group in the match. Similarly, we've placed the last part of the string in a group, and used a zero-width lookahead assertion. Grouping Constructs on MSDN shows the groups as well as the assertions.
resultString = Regex.Replace(
im_cfg_contents,
#"(?<=\$displayHeight[\s]*=[\s]*"")(.*)(?="";)",
Convert.ToString(y_res));
Another approach would be to use the following code. The modification to the regular expression is just placing the first part in a group and the last part in a group. Then in the replace string, we add back in the first and third groups. Not quite as nice as the first approach, but not quite as bad as writing out the $displayHeight part. Substitutions on MSDN shows how the $ characters work.
resultString = Regex.Replace(
im_cfg_contents,
#"(\$displayHeight[\s]*=[\s]*"")(.*)("";)",
"${1}" + Convert.ToString(y_res) + "${3}");
Try this:
resultString = Regex.Replace(
im_cfg_contents,
#"\$displayHeight[\s]*=[\s]*""(.*)"";",
#"\$displayHeight = """ + Convert.ToString(y_res) + #""";");
It replaces the whole string because you've matched the whole string - nothing about this statement tells C# to replace just the matched group, it will find and store that matched group sure, but it's still matching the whole string overall.
You can either change your replacer to:
#"\$displayHeight = """ + Convert.ToString(y_res) + #""";"
..or you can change your pattern to just match the digits, i.e.:
#"[0-9]+"
..or you could see if C# regex supports lookarounds (I'm not sure if it does offhand) and change your match accordingly.
You could also try this, though I think it is a little slower than my other method:
resultString = Regex.Replace(
im_cfg_contents,
"(?<=\\$displayHeight[\\s]*=[\\s]*\").*(?=\";)",
Convert.ToString(y_res));
Check this pattern out
(?<=(\$displayHeight\s*=\s*"))\d+(?=";)
A word about "lookaround".