Hi!!!
I am using following code in which I am generating the latex format.
Here I want to use the combination of characters[A-Za-z], numbers[0-9] ,special charactes(like π ,θ ,α ,β ,γ ,°,+, - ,×,÷,√ ,(,)etc) ,decimal numbers. For entering special characters I have used toolbar

Can anyone tell me how to create regular expression for above together.
The code which I am using is as follows:

const string matchNumerator = @"\((?<Numerator>[\d,]*(\.\d*)*)\)";
             const string matchDenominator = @"\((?<Denominator>[\d,]*(\.\d*)*)\)";
             const string matchBoth = matchNumerator + @"\/" + matchDenominator;
             
                         System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(input, matchBoth);
             
                 decimal dNumerator, dDenominator;
                if (decimal.TryParse(m.Groups["Numerator"].Value, out dNumerator) && decimal.TryParse(m.Groups["Denominator"].Value, out dDenominator))
                 {
                     //and this right here is the string in latex format
                     string latex = @"\frac {" + dNumerator.ToString() + "}{" + dDenominator.ToString() + "}";
                     input = input.Remove(m.Index, m.Length);
                     input = input.Insert(m.Index, latex);
                 
                 }

Kindly provide me solution...............

Recommended Answers

All 32 Replies

You don't necessarily want a regex for that.... it will likely get a little too complicated.

private static char[] GetChars()
    {
      List<char> lst = new List<char>();
      lst.Add('π');
      lst.Add('θ');
      lst.Add('α');
      lst.Add('β');
      lst.Add('γ');
      lst.Add('°');
      lst.Add('+');
      lst.Add('-');
      lst.Add(',');
      lst.Add('×');
      lst.Add('÷');
      lst.Add('√');
      lst.Add(',');

      for (int i1 = (int)'a'; i1 < (int)'z'; i1++) lst.Add((char)i1);
      for (int i1 = (int)'A'; i1 < (int)'Z'; i1++) lst.Add((char)i1);
      for (int i1 = (int)'0'; i1 < (int)'9'; i1++) lst.Add((char)i1);
      
      return lst.ToArray();
    }

    private static readonly char[] allowedCharacters = GetChars();

    private void button6_Click(object sender, EventArgs e)
    {
      string input = "abc12312312sd__@#$";
      foreach (char c in input)
      {
        if (!allowedCharacters.Contains(c))
        {
          MessageBox.Show("Invalid input");
          return;
        }
      }

      const string matchNumerator = @"\((?<Numerator>[\d,]*(\.\d*)*)\)";
      const string matchDenominator = @"\((?<Denominator>[\d,]*(\.\d*)*)\)";
      const string matchBoth = matchNumerator + @"\/" + matchDenominator;

      System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(input, matchBoth);

      decimal dNumerator, dDenominator;
      if (decimal.TryParse(m.Groups["Numerator"].Value, out dNumerator) && decimal.TryParse(m.Groups["Denominator"].Value, out dDenominator))
      {
        //and this right here is the string in latex format
        string latex = @"\frac {" + dNumerator.ToString() + "}{" + dDenominator.ToString() + "}";
        input = input.Remove(m.Index, m.Length);
        input = input.Insert(m.Index, latex);

      }
    }

thanks for your reply but I am getting following error :

Error 1 'System.Array' does not contain a definition for 'Contains' and no extension method 'Contains' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)

Kindly give some solution...........

thanks for your reply but I am getting following error :

Error 1 'System.Array' does not contain a definition for 'Contains' and no extension method 'Contains' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)

Kindly give some solution...........

thanks for your reply but I am getting following error :

Error 1 'System.Array' does not contain a definition for 'Contains' and no extension method 'Contains' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)

Kindly give some solution...........

try replacing private static char[] GetChars() with private static List<char> GetChars() and private static readonly char[] allowedCharacters = GetChars() with private static readonly List<char> allowedCharacters = GetChars()

try replacing private static char[] GetChars() with private static List<char> GetChars() and private static readonly char[] allowedCharacters = GetChars() with private static readonly List<char> allowedCharacters = GetChars()

Ryshad it is still giving the error in the line:"return lst.ToArray();"
and the error is:Cannot implicitly convert type 'char[]' to 'System.Collections.Generic.List<char>'

The problem you have with my original code is your dont have a "using System.Linq;" at the top of your class.

Aah, my bad. I've not worked with Linq :p

All the server downs didnt exactly help with following a train of thought either lol

LINQ is awesome ;) Not necessarily the Linq-to-Sql stuff, although that is nice, but the extension methods are awesome++++++.

I'll have to look into it :)

LINQ is awesome ;) Not necessarily the Linq-to-Sql stuff, although that is nice, but the extension methods are awesome++++++.

I have already added System.Data.Linq;
Still its giving error................

I am getting error in line:

return lst.ToArray();

and the error is
:Cannot implicitly convert type 'char[]' to 'System.Collections.Generic.List<char>'

Kindly help me..........

It sounds to me like you didn't undo all of the changes you made to the code.

private static char[] GetChars()

Make sure your return type is char[] and not List<char>

Thanks for your reply Mr.Scott.......
I want to use all characters for fraction but here if am using any other character except digits,its not giving me correct latex form.
And if I enter only digits its giving me correct latex format and not with other characters.
My application is attached here.
Kindly help me to get correct output.

Kindly provide me some solution..................

Sir Scott , I am waiting for your reply .................
Kindly help me ...............

Daniweb Help!!!..............
I am not able to find any solution.........

I've just downloaded and looked over the project you attached and im not even sure where to start.

Firstly, a few of your input.replace() calls have white space in the search string. Are they supposed to be there? ie:

input = input.Replace("  alpha", "\\alpha");
// if input was "12  alpha 1" it would become "12\\alpha 1" but if the string was "12 alpha 1" it wouldnt change because "  alpha" != " alpha".

Next, when you use sqrt() or \\sqrt{} is there a number inside the brackets/bracers? If so, then input = input.Replace("sqrt()", "\\sqrt{}"); will not work. You need to extract the number, altering the regular expression that sknake gave you will allow you to do this.

Finally (but definitely not least), you have commented out the code that sknake gave you that handles the allowed characters so you arent actually checking your string for allowed chars.
You said

I want to use all characters for fraction

. Do you mean you only want to allow the fraction characters such as 'π'/'∞'/'ω'/etc or do you mean you want to allow ALL characters: letters/punctuation/etc?

I moved the FormatText() method into a test app as is and it runs. The Regex replaces fractions and the replace methods pick out the strings correctly. It wont flag invalid input as you have removed that code.

Potential problems:

a) you are missing some input.replace calls. I noticed there were characters in your GetChars() list that werent handled by an input.replace.

b) your input.replace calls are not matching strings the way you would like. See above regarding white space and numbers. String.Replace will only replace an exact match. So " γ" wont match "γ"..be very careful of whitespace in string matches.

c) You are not feeding the correct format into your NativeMethods.CreateGifFromEq() method. You need to go through your FormatString() method and ensure that the string is being correctly ordered and constructed. Maybe whitespace is being added where it shouldnt etc.

d) Your input contains invalid data. I cant run the linq code as i dont have latest .net : / But the code sknake gave you looks sound. You need to get that working to detect and flag any invalid characters.

You have been given all the tools you need to get this done; it may seem like a complicated issue, but at the heart of it it is just a string manipulation. Read up on regex and string functions and go over the code you have been given. You have everything you need to replace the readable characters with latex ones :)

Thanks for your reply,Ryshad.....
1. I have used whitespace just to just to make each character clearly visible.
2.For sqrt() when i am using a number inside it it is giving correct result.
3.The code which sknake has given me was not working....when I was trying to execute it the application was not responding.So I ahve to comment some part of the code.....
4.For fraction I want the combination of all or any character (not just digits.)Because its working fine for digits but not with the combination of other characters ,alphabets etc....
5.And I am not able to implement for fraction if I use alphabets or other characters.
6.Also the code which sknake has given it is not implementing with the code of regular expression.
6.And for the first time when I click on fraction button it given correct latex format as we see in books ,but when in the same string when i am using it for second time its not giving correct result .You can see teh example in the thumbnail attached....

Please help me out........
It seems to be a very big problem to me......

When i gave you the combination of sknakes suggestions i wrote in a while(m.Match == true) loop. You subsequently removed it. The loop was there to ensure that multiple instances of fractions were found and handled.

Here is a revised version, it will allow letters or numbers in the fractions and handle multiple occurances of fractions in the string:

const string matchNumerator = @"\((?<Numerator>[\da-zA-Z]*(\.[\da-zA-Z]*)*)\)";
            const string matchDenominator = @"\((?<Denominator>[\da-zA-Z]*(\.[\da-zA-Z]*)*)\)";
            const string matchBoth = matchNumerator + @"\/" + matchDenominator;

            //const string txtBoxInput = @"((2a)/(b))/((3)/(4))";
            System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(input, matchBoth);
            while (m.Success)
            {
                string sNumerator = m.Groups["Numerator"].Value;
                string sDenominator = m.Groups["Denominator"].Value;
                string latex = @"\frac {" + sNumerator.ToString() + "}{" + sDenominator.ToString() + "}";
                input = input.Remove(m.Index, m.Length);
                input = input.Insert(m.Index, latex);


                 m = System.Text.RegularExpressions.Regex.Match(input, matchBoth);
            }

I really can't stress enough the importance of understanding the code you are given. I edited sknakes regular expression using a syntax reference online; I havent done a lot of work with regex, i havent been trained in it, i just figured it out. If you spent a little time reading up on the code you would be able to edit it to allow letters yourself.

The same goes for the while loop. When i gave you the code the first time it could handle multiple instances of frac()/(). You said you understood what the code was doing, yet you took it out and then complained that it doesnt do it any more.

If you go away and fix it yourself, experiment with it and read about it, you will understand the principles and be able to apply them to new problems.
Thats what sknake and i and the other solvers on the boards have done, we have done the reading, we have experimented with the code, we have found solutions. Thats how we can offer solutions, its not that we have solved the SAME problems before, its because we have solved SIMILAR problems, and because we understood how our solution worked we are able to adapt it to solve other peoples problems.

This is not intended as a rant, i am just trying to stress the importance of understanding the code we give you. If you keep asking us to fix it for you, you arent learning anything. We will happily help you to understand the code, but you need to do some of the work yourself, the best way to learn is to write the code yourself. Coding is a learning process, i've been writing code for years and i am still learning new things.

Thanks for your reply.........
I am working on teh code when I'll finish i'll let you know............
Can you guide me for one more thing:
How can I use the code given by sknake for the fraction code:

private static char[] GetChars()
             {
                List<char> lst = new List<char>();
                lst.Add('π');
                lst.Add('θ');
                lst.Add('α');
                lst.Add('β');
                lst.Add('γ');
                lst.Add('°');
                lst.Add('+');
                lst.Add('-');
                lst.Add(',');
                lst.Add('×');
                lst.Add('÷');
                lst.Add('√');
                lst.Add(',');
        for (int i1 = (int)'a'; i1 < (int)'z'; i1++) lst.Add((char)i1);
        for (int i1 = (int)'A'; i1 < (int)'Z'; i1++) lst.Add((char)i1);
        for (int i1 = (int)'0'; i1 < (int)'9'; i1++) lst.Add((char)i1);
 
        return lst.ToArray();
             }

I think i finally see the root of some of the problems. The code sknake gave you would search the contents of a string for any invalid characters. He thought you wanted to ensure the user only entered a valid string.

I have just re-read the whole of this thread and i think i now understand what you were asking. You want to alter the regular expression we gave you so that it will allow special characters INSIDE the fraction. Is that correct? Such as "(2b)/(θ)".

i think the problem may have been a language barrier, is English your first language? Your post wasn't 100% clear what you wanted, its only by piecing together some of the things you've said in response to our posts that i've reached this conclusion.

The following regex will match ANYTHING inside the brackets. Using the code as i gave it to you, with the loop, it will also work for nested fractions so ((2a)/(b))/((3)/(4)) became \frac {\frac {2a}{b}}{\frac {3}{4}} when i ran it.

const string matchNumerator = @"\((?!\()(?<Numerator>[^\)]*?)\)";
            const string matchDenominator = @"\((?!\()(?<Denominator>[^\)]*?)\)";
            const string matchBoth = matchNumerator + @"\/" + matchDenominator;

Hope this is what you wanted :)
Remember to mark the thread as solved if this fixes the issue.

Thanks Ryshad,
You understood what I mean to say.

I have just re-read the whole of this thread and i think i now understand what you were asking. You want to alter the regular expression we gave you so that it will allow special characters INSIDE the fraction. Is that correct? Such as "(2b)/(θ)".

Yes I want to allow special characters like 'π'(pi) ,'θ'(theta), 'α'(alpha),'β'(beta),'γ'(gamma),'°'(degree),'+'(plus), '-' (minus), ',' (comma),'×'(multiply),'÷'(divide),'√'(squareroot) etc. inside fraction.... such as (23π+5-78β√(23))/(9pα,ij).
I am working on your code ,when I'll finish let you know......
Anyways thanks a lot...........

Ive just noticed a problem with the regex : / It considers the first ) it finds to be the closing bracket...which means it doesnt match (23π+5-78β√(23)) correctly. Is the '/' symbol used for anything at all other than fractions? If fractions are the only time that the '/' symbol is used then i have a fix. if not i'll need to look at it again.

Ive just noticed a problem with the regex : / It considers the first ) it finds to be the closing bracket...which means it doesnt match (23π+5-78β√(23)) correctly. Is the '/' symbol used for anything at all other than fractions? If fractions are the only time that the '/' symbol is used then i have a fix. if not i'll need to look at it again.

Ryshad ,
Yes , '/' is used at other places also and for (23π+5-78β√(23)) its not matching correctly.....This can be seen in the thumbnail(frac.gif) attached......

Also in the thumbnail2(example.gif) , when I am using square bracket '[] ' it gives correct result but for parenthesis '()' it gives wrong result.

As i said, the expression considers the first ')' to be the closing bracket. If the '/' is used elsewhere then its a more complex task as you need to check for balanced groups within the brackets. I'll have a fiddle and let you know if i find a working regex for you.

As i said, the expression considers the first ')' to be the closing bracket. If the '/' is used elsewhere then its a more complex task as you need to check for balanced groups within the brackets. I'll have a fiddle and let you know if i find a working regex for you.

Okkk!!!

Right,

I took a LOT of reading and experimenting. But i finally mastered Recursion, Named Groups and Balanced Groups to create the following:

const string matchNumerator = @"\((?<Numerator>((?<p>\()|[^\(\)]|(?(p)(?<-p>\))|))*)\)";
            const string matchDenominator = @"\((?<Denominator>((?<p>\()|[^\(\)]|(?(p)(?<-p>\))|))*)\)";
            const string matchBoth = matchNumerator + @"\/" + matchDenominator;

I have tested it with the while loop in place as i gave it to you and this handles everything i could think to test it with. It copes with nested fractions as well as nested brackets within a fraction and accepts any character inside the fractions.

I have to admit that for a novice, putting together this pattern would have been daunting...it took me hours of experimentation :p It has been a fun learning curve and i feel a LOT more confident with regex as a result, which is the point i've been making all along :)

Please remember to mark the thread as solved, now i'm going to rest my brain for a half hour or so.

Just as a quick aside, to anyone reading this that wants to learn i figured i could break down the regex for you :p

I have attached it as an image since i couldnt get the table format to fit nicely in a post...if anyone knows how to add a table inside a post drop me a PM ;)

The denominator is the same as the numerator. Hope this helps someone and saves them the brain lashing i went through haha

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.