Regex c# là gì

A regular expression is a sequence of characters used to match a pattern to a string. The expression can be used for searching text & validating đầu vào.

Bạn đang xem: Regex c# là gì

Rethành viên, a regular expression is not the property of a particular language.

POSIX is a well-known library used for regular expressions in C.


*

Patterns in the POSIX library

ExpressionDescription
<>Used lớn find any of the characters or numbers specified between the brackets.
<:number:>Used khổng lồ find any digit.
<:lower:>Used khổng lồ find lowercase alphabets.

Xem thêm: Nơi Bán Kem Trị Mụn An Bảo 30 Viên, Kem Ngừa Mụn An Bảo

<:word:>Used to lớn find letters numbers & underscores.

Creating a regular expression

The regcomp() function is used to compile a regular expression. According to lớn the official documentation, it takes three arguments:

A pointer khổng lồ the memory location where the pattern to be matched is stored.A pointer khổng lồ a pattern of the string type.A flag lớn specify the type of compilation.

It returns a 0 upon successful compilation,​ và an error code otherwise.


#include// Importing the POSIX regex library#include int main() regex_t regex; int return_value; return_value = regcomp(®ex,"<:lower:>",0); if (return_value == 0) printf("Regular expression compiled successfully."); else printf("Compilation error."); return 0;

Matching a pattern

The regexec() function is used lớn match a string against a pattern. According to lớn the official documentation, it takes in five sầu arguments:

A precompiled patternA string in which the pattern needs to lớn be searched for.Information regarding the location of matches.Information regarding the location of matches.Flags to lớn specify a change in the matching behavior.

It returns a 0 if there is a match, và a REG_NOMATCH error otherwise.


#include// Importing the POSIX regex library#include void print_result(int return_value) if (return_value == 0) printf("Pattern found. "); else if (return_value == REG_NOMATCH) printf("Pattern not found. "); else printf("An error occured. "); int main() regex_t regex; int return_value; int return_value2; return_value = regcomp(®ex,"ice",0); return_value = regexec(®ex, "icecream", 0, NULL, 0); return_value2 = regcomp(®ex,"ice",0); return_value2 = regexec(®ex, "frozen yoghurt", 0, NULL, 0); print_result(return_value); print_result(return_value2); return 0;

#include#includeint main() char name<15>; // Taking a name as an đầu vào. // name can only include alphabets scanf("%",name); printf("%s",name); return 0;