Regular expression, numbers?

I made a code that translates strings to match each word from array 0ne to array two and display the correct results. But how to let the compiler take the number on the line and print it as it is, ummmm see the code I wrote


class Program
    {
        public static string[] E = { "i", "go", "school", "to", "at" };
        public static string[] A = { "Je", "vais", "ecole", "a", "a" };

        public static string Translate(string s)
        {
            string str = "";
            Regex Expression = new Regex(@"[a-zA-Z]+");
            MatchCollection M = Expression.Matches(s);
            foreach (Match x in M)
                str = str + " " + TranslateWord(x.ToString());
            return str;
        }

public static string TranslateWord(string s)
        {
            for (int i = 0; i < E.Length; i++)
                if (s.ToLower() == E[i].ToLower())
                    return A[i];
            return "Undefined";
        }

      


here I want to enter the whole string and the code has to translate it with a number, now I know how to make a word (by merging and translating them) but what about numbers)

        static void Main(string[] args)
        {
            string str = "I go to school at 8";
            Console.WriteLine(Translate(str));
        }

      

how to continue ?!

0


source to share


4 answers


Change the regex to [a-zA-Z0-9]+



By the way, why don't you use a method String.Split

instead of Regex?

+4


source


This regex will work better when you actually start typing accents on your French words and you want to split the French string:

\w+

      



In .NET, \ w contains all letters and numbers from all scripts, not just the English az and 0-9.

+1


source


Here's a hint:

public static void process (String s) {
    String [] tokens = s.split("\\s+");
    for (String token : tokens) {
        if (token.matches("[A-Za-z]+")) {
            System.out.println("  word: '" + token + "'");
        } else if (token.matches("[0-9]+")) {
            System.out.println("number: '" + token + "'");
        } else {
            System.out.println(" mixed: '" + token + "'");
        }
    }
}

      

Wnen, called for example ...

process("My 23 dogs have 496 fleas.");

      

... it produces the following:

  word: 'My'
number: '23'
  word: 'dogs'
  word: 'have'
number: '496'
 mixed: 'fleas.'

      

0


source


If your regix engine supports it, I use [: alnum:] (that is, the POSIX classes), which makes the regex more portable. As usual, beware of locale issues.

0


source







All Articles