Regex c# là gì

A regular expression is a sequence of characters used khổng lồ match a pattern to lớn a string. The expression can be used for searching text & validating input.

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

Remember, 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 khổng lồ find any of the characters or numbers specified between the brackets.
<:number:>Used khổng lồ find any digit.
<:lower:>Used lớn find lowercase alphabets.

Xem thêm: Download Tải Game Phá Nhà Hàng Xóm Tinh Nghịch 1, 2, 3 Full Cho Pc

<:word:>Used to find letters numbers và underscores.

Creating a regular expression

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

A pointer khổng lồ the memory location where the pattern khổng lồ 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,​ and 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 to match a string against a pattern. According lớn the official documentation, it takes in five arguments:

A precompiled patternA string in which the pattern needs 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, and 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;