C# regular expression engine does not work [closed] - c#

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
i'm doing the simplest regex.match ever, i am giving the Regex.Match a pattern of one character and it returns no match at all, and i made sure the input text contains a lot of that character?
i checked all the usings.
its just very weird.
any help would be appreciated!
Thanks.
EDIT:
my sample is "doing any type of matching is simply not WORKING"
returns an empty match
Match m=Regex.Match(#"c","abcdc");
the code is compiled with no errors, so why the NO MATCHING!!

EDIT: based on your edit the issue is that you're using the parameters out of order. You need to switch the order and supply the input (string source to find a match in) then the pattern (what to match against).
In fact, this order is specified for you by the IntelliSense as depicted in this image:
It usually helps to match the naming suggested by the IntelliSense or refer to it to ensure the proper items are being passed in.
What is the character being used? Chances are you're trying to use a character that is actually a metacharacter which holds special meaning in regex.
For example:
string result = Regex.Match("$500.00", "$").Value;
The above wouldn't return anything since $ is a metacharacter that needs to be escaped:
string result1 = Regex.Match("$500.00", #"\$").Value; // or
string result2 = Regex.Match("$500.00", "\\$").Value; // or
string result3 = Regex.Match("$500.00", Regex.Escape("$")).Value;
For a list of common metacharacters that need to be escaped look at the Regex.Escape documentation.

You have the parameters in the wrong order in your example:
Match m=Regex.Match(#"c","abcdc");
This code means that you try to find the string "abcdc" in the string "c", try it the other way around and it should work better, ie:
Match m=Regex.Match("abcdc", "c");
Also, the fact that your code compiles doesn't mean that it will necessarily find a match...
Here is the documentation for Regex.Match.

I assure you, the regular expression works. I have used it many, many times.
This will put the string "d" in the variable s:
string s = System.Text.RegularExpressions.Regex.Match("asdf", "d").Value;
If that doesn't work, perhaps you have some strange culture setting that affects how strings are compared? Does System.Globalization.CultureInfo.CurrentCulture.DisplayName return an expected value?

Related

Regular expression comparison [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I want to check whether my string variable contain the particular regular expression pattern or not
xxx-xx-x
(x is numerical value) using c#. If it contains then I need to return true or false.
Can anyone please help me to resolve this issue..
Use the returned value by Regex.IsMatch().
Regex regex = new Regex("[0-9]{3}-[0-9]{2}-[0-9]");
bool containsPattern = regex.IsMatch(stringToVerify);
This is the regex you are looking for
\b\d{3}-\d{2}-\d\b
\b is a boundary..If you don't use it,you would also match 111-22-345 or 111-22-3-33 which i guess you don't want to match
using System.Text.RegularExpressions;
public static bool ControlRegex(string input)
{
Match match = Regex.Match(input, #"([A-Za-z0-9\-]+)",RegexOptions.IgnoreCase);
if (match.Success)
{
return true;
}
}
You can try something like this... You have to put correct regular expression to secend parametre of Regex.Match...
You can find the correct regex with a regex program. For example "RegEx TestBed" you can download it from here; http://regextestbed.codeplex.com/releases/view/60833 with this program, you put your text in text area, and in pattern area you try to find correct regex. And below, in the the list area, and program shows you the matches according your regex, so you can try and find your correct regex...

How do I insert tabs into strings for a C# console application? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
This console application will write .txt files to disc.
User wants to import these .txt files into Excel such that they are formatted correctly, so I plan to use tabs.
I keep getting this nonsense "Some string /t some other string /t/t some other string". There is no Environment.Tab like there is Environment.NewLine.
How do I get the tabs and not /t into my strings?
I'm sure there's a way and it'll probably be so obvious that I'll have to call myself faint all day on response.
(I'm open to other solutions as well. I might have to use | or some other delimiter/character.)
Tabs in strings are typically written \t, not /t. Are you escaping your string correctly?
If the purpose is to create text files which will eventually be imported int excel why don't you use comma separated values. More info
http://en.wikipedia.org/wiki/Comma-separated_values
Technically there is tab constant in .NET. It is in Microsoft.VisualBasic.dll.
var tab = Microsoft.VisualBasic.Constants.vbTab;
But there is no reason to use vbTab, you can just use \t with the same result.
If you really feel disgusted by this \t question, why not write a simple utility class
public static class MyUtility
{
public static string Tab
{
get{return "\t";}
}
}
now you can use in your code to build your tab separated strings....
string test = "MyFirstString" + MyUtility.Tab + "MySecondString" + MyUtility.Tab .......
but, again, WHY?, there is no reason to not use the predefined standard escape sequence

What is the regex for this? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
First of all I guess I will start by asking what are some good tools or references for building regex strings? I usually find them on the net, but I would love to learn them a little more.
Now on to my original question: what is the Regex to find a full string, or find a line that contains the string. The string is:
** Start of
The regex you are looking for is: \*\* Start of.*
Because C# has its own escape characters you may want to put this in a verbatim string like #"\*\* Start of.*".
The best tool for helping you build, learn and understand regular expressions is RegexBuddy. It helps you see the meaning of your expressions as well as test them through an intuitive graphical UI.
The most complete resource for information on regular expressions (across different languages) is http://www.regular-expressions.info/ . If you are looking to learn about a specific Regular Expression implementation you might be better of reading the implementation-specific documentation/spec. For .NET, a good starting place would be the Regex documentation at MSDN You can also test .NET regular expressions quickly online with the free tool available at http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx
I also would like to note that I agree with #ziesemer that using an IndexOf or StartsWith method is probably a better solution for such a simple pattern.
I think you're using the wrong tool for the job. Regular expressions are best suited for finding patterns. It seems you're only looking to do a simple search - use the proper API (e.g. IndexOf) for this.
Otherwise, you simply need to escape the asterisks - which are special characters in regular expressions - meaning "match 0 or more of":
\*\* Start of
While very informative, none of the answers provide the correct regex for your specific problem. Here it is:
string regexPattern = #"^.*?\*{2} Start of.*?$";
Note that you will have to specify multiline option when searching for match.
You can see the results here.
And here's the explanation of the pattern:
^.*?\*{2} Start of.*?$
Options: ^ and $ match at line breaks
Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Match any single character that is not a line break character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “*” literally «\*{2}»
Exactly 2 times «{2}»
Match the characters “ Start of” literally « Start of»
Match any single character that is not a line break character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Assert position at the end of a line (at the end of the string or before a line break character) «$»
For learning regex you could check the Regular Expression Basic Syntax Reference on www.regular-expressions.info and also additionally A Gentle Introduction: The Basics
And regarding the string to find if you want only character from a to z then I think you should write as
^[a-zA-Z]$
This will take small and capital a to z characters.
Update
^\*\* Start of(.*?)$
Spliting Detail
\*, take asterisk into consideration
Start of, compare exactly the this string
(.*?), take anything on that single line
^\*\* Start of(.*?)(([\n]*(.*?)){19})*$
Spliting Detail
\*, take asterisk into consideration
Start of, compare exactly the this string
(.*?)(([\n]*(.*?)){19})*, take anything but limit upto 19 lines

Extracting double/decimal number from string? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I need to extract the value 33345.002 from the following string:
"ABC(MAX)(33345.002)"
How can I perform this in C#?
I tried handling it in SQL but was picking up the (MAX) too so now I'm gonna try C#.
Thanks
.
.
.
This is the closest so far :
string temp = "YYY(33345.002)(gg)YYYY";
temp = Regex.Replace(temp, "[^.0-9]", "");
double num;
bool success = Double.TryParse(temp, out num);
if (success)
{
//do what ever to the number}
but there is a problem, some of the numbers have zeros in front of them. like: 00033.33
This is really pretty simple.
Declare the characters you want to grap [0-9]/"0123456789" as a constant in C#
loop through the string, example:
public bool TryParseDouble(string input, out double value){
if(string.IsNullorWhiteSpace(input)) return false;
const string Numbers = "0123456789.";
var numberBuilder = new StringBuilder();
foreach(char c in input) {
if(Numbers.IndexOf(c) > -1)
numberBuilder.Append(c);
}
return double.TryParse(numberBuilder.ToString(), out value);
}
Ofcoarse this could be enhanced (perhaps just parse out the first number, or return an array of doubles parsing out all numbers) - not to mention it will parse out multiple decimals which is not exactly what you want.
The same technique can be used in T-SQL as well with looping over the string, declaring the valid values then using 'in'.
EDIT: On second thought
Regex.Match(input, #"\d+(.\d+)?")
would extract double/decimal from string then you could just use double.Parse if a match is found :).
EDIT 2: Btw for some silly reason '\ .' gets escaped as '.' on Stack Overflow. Just note that the decimal in the regex is escaped (just . matches anything)
Happy coding!
You need the same regex (including the enhancements mentioned) as provided as the top answer by J-16 SDiZ for this SO: Regular expression for decimal number, but without the ^ at the beginning and $ at the end.
Next time it might be worth searching a bit on SO or Google first :)

How to form this Regex [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Suppose the string is:
string item = "t-ewrwerwerwerwer\r-rr\wrjkwlr";
I want to Replace all - except when it is preceded by r.
So resut will be
string cleanItem = "tewrwerwerwerwer\r-rr\wrjkwlr"'
What regular expression can be used?
I think this regular expression is a little more efficient:
-(?<!r-)
Or if your language doesn’t support negative look-behind assertions, use this expression:
(^|[^r])-
and replace it by \1 (first matching group).
A replacement on (?<!r)- by an empty string should do the trick I think.
(?<!r)-
As long as your regex flavor supports zero-width look-behind, that is.

Categories