Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

Elena123456 avatar Elena123456 235 Точки

06. Extract Emails-Runtime error

Can somebody please explain to me why do I get in Judge- "Unhandled exception. System.Text.RegularExpressions.RegexParseException: Invalid pattern '(?<=\s)(?<user>(?![\_])[A-za-z0-9]+(?:[-\.\_][A-za-z0-9]+)*)@(?<host>[a-zA-Z]+(?:[\-][a-zA-z]+)*(?:\.[a-zA-Z]+(?:[\-][a-zA-Z]+)*)*\.[a-z]+)' at offset 21. Unrecognized escape sequence \\_."

Althouth in https://regex101.com/ and in https://regexr.com/ my regex is working correctly- match the valid  and doesn't match the invalid emails:

 valid email: info@softunibulgaria.org, kiki@hot-mail.co.uk, no-reply@github.com,
s.peterson@mail.uu.net, info-bg@software-university.software.academy support@github.com


invalid email: --123@gmail.com, …@mail.bg, .info@info.info, _steve@yahoo.cn,
mike@helloworld, mike@.unknown.soft., s.johnson@invalid-.

 

https://softuni.bg/trainings/resources/officedocument/49595/regular-expressions-exercise-csharp-fundamentals-may-2020/2830

https://judge.softuni.bg/Contests/Compete/Index/1668#5

using System;
using System.Text.RegularExpressions;
namespace text
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            string input = Console.ReadLine();
            Regex regexForEmail=new Regex(@"(?<=\s)(?<user>(?![\_])[A-za-z0-9]+(?:[-\.\_][A-za-z0-9]+)*)@(?<host>[a-zA-Z]+(?:[\-][a-zA-z]+)*(?:\.[a-zA-Z]+(?:[\-][a-zA-Z]+)*)*\.[a-z]+)");
            MatchCollection matchesEmail = regexForEmail.Matches(input);
            if (regexForEmail.IsMatch(input))
            {
                foreach (Match match in matchesEmail)
                {
                    Console.Write(match.Groups["user"]);
                    Console.WriteLine(match.Groups["host"]);
                }
            }

        }
    }
}

Тагове:
0
C# Fundamentals 24/11/2020 14:02:47
Axiomatik avatar Axiomatik 2422 Точки
Best Answer

Regex is also not running in VS, not just judge. I used this simpler Regex for this problem.

Best,

 

using System;
using System.Text.RegularExpressions;

namespace extractEmails
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = Console.ReadLine();
            string pattern = @"(^|(?<=\s))(([a-zA-Z0-9]+)([\.\-_]?)([A-Za-z0-9]+)(@)([a-zA-Z]+([\.\-][A-Za-z]+)+))(\b|(?=\s))";
            Regex regex = new Regex(pattern);
            MatchCollection matches = regex.Matches(text);
            if (regex.IsMatch(text))
            {
                foreach (Match email in matches)
                {
                    Console.WriteLine(email);
                }
            }
        }
    }
}


 

1
Elena123456 avatar Elena123456 235 Точки

And thanks to you I have founded the mistake in my regex and I have learnt something new. I'am very happy and I'am very greatfull about that. :)

Regex is not running in VS and in Monodevelop when in front of  "_" we put escape symbol "\".

I have barrowed this part of your regex :

[\.\-_]

 and have deleted my "[-\.\_]". 

And in the beginning in my regex I have replaced "?![\_]"  with "?![_]".

Regex regexForEmail=new Regex(@"(?<=\s)(?<user>(?![_])[A-za-z0-9]+(?:[\.\-_][A-za-z0-9]+)*)@(?<host>[a-zA-Z]+(?:[\-][a-zA-z]+)*(?:\.[a-zA-Z]+(?:[\-][a-zA-Z]+)*)*\.[a-z]+)") ;

And now my regex is also valid and Judge gave to my code 100/100. :) https://pastebin.com/r6cZbrz5

Your regex  is better than mine and I going to take a better look at it when I go home after work.

All the best!

Eli

1
24/11/2020 14:04:05
Elena123456 avatar Elena123456 235 Точки

Axiomatic, hello again!

I have taken a better look at your regex. I can't understand the begining:

(^|(?<=\s)

Why have you used operator "or" at the begining in your regex? If you have time to help me understand it I would realy appreciate it.

I see that your regex match and this email adress: "elena@abv-bg". I have made my regex more complicated, because I have assumed that Judge would be looking for a "." at the end, but I have assumed wrong.

By the way from today I have a new laptop with Windows 10 and VisualStudio 2019. I rushed and bought it earlier than I planned, because you mentioned that there is a potential risk to start Advanced module working on Monodevelop.Thanks a lot! :)

 

0
Axiomatik avatar Axiomatik 2422 Точки

No idea anymore, I just used different types of Backreferences/Lookahead/LookBehind and regex combinations until I found something that worked. But the regex on the exam won't be that complex and this exercise was more like a bonus assignment. Good luck with your new laptop and hopefully no more problems with C# code that won't compile with MonoDevelop.

Best,

1
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.