Regex example часто используемые регулярные выражения примеры
Зачем нужны регулярные выражения?
Регулярные выражения (Regex) - это язык, с помощью которого можно анализировать текст. Анализ проводится по нечетким критериям и позволяет найти подстроку, в которой есть какие-то дополнительные несущественные символы. Этот механизм довольно часто применяется при: парсинге сайтов, замена и поиск информации в тексте, анализ логов приложений. Есть масса преимуществ, которые открываются с регулярными выражениями. Каждому программисту хоть раз в его работе приходилось использовать регулярные выражения. Несколько примеров, используемые мной лично я привожу здесь. Быть может это поможет кому-то для решения их задач.
Regular Expression Operators
a? | matches 0 or 1 occurrence of *a* |
a* | matches 0 or more occurrences of *a* |
a+ | matches 1 or more occurrences of *a* |
a|b | match *a* or *b* |
. | match any single character |
[woe] | match any of the named characters 'w', 'o', 'e' |
[1-9] | match any of the characters in the range |
[^157] | match any characters not named |
(ie) | group an expression (for use with other operators) 'ie' |
^a | match an *a* at the beginning of a line |
a$ | match an *a* at the end of a line |
\d | Any digit, short for [0-9] |
\D | A non-digit, short for [^0-9] |
\s | A whitespace character, short for [ \t\n\x0b\r\f] |
\S | A non-whitespace character, for short for [^\s] |
\w | A word character, short for [a-zA-Z_0-9] |
\W | A non-word character [^\w] |
\d{1,4} | {} describes the order of the preceding liberal. In this example \d must occur at least once and at a maximum of four |
X? | Finds no or exactly one letter X, is short for {0,1} |
X*? | ? after a qualifier makes it a "reluctant quantifier", it tries to find the smallest match |
Example 1
Text: cord nord ford
Regular expression: [^cn]ord
Result: ford
Example 2
Text: Mary had a little lamb
Regular expression: .a
Result:
Mary
had
a little
lamb
Example 3
Text:
jkl abc xyz
jkl xyz abc
jkl abc abc
jkl xyz xyz
Regular expression: (abc|xyz)
Result:
abc
xyz
abc
yz
Regular expression: (abc|xyz) \1
Result:
abc abc
xyz xyz
Regular expression: (abc|xyz) (abc|xyz)
Result:
abc xyz
xyz abc
abc abc
xyz xyz
Example 4
Text: <p id="test">p1</p> <p id="test">p2</p>
Regular expression: <p id="test">(.+)</p>
Result Groups[0]: <p id="test">p1</p> <p id="test">p2</p>
Result Groups[1]: p1</p> <p id="test">p2
Regular expression: <p id="test">(.+?)</p>
Result Groups[0]:
<p id="test">p1</p>
<p id="test">p2</p>
Result Groups[1]:
p1
p2
Example 5
Text: IP Numbers 66.70.7.154
Regular expression: ([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})
Result: 66.70.7.154
Example 6
Text: Floating Point Number -123.45
Regular expression: [-+]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?
Result: -123.45
Example 7
Text: Date d/m/yy and dd/mm/yyyy >> 09/12/2005
Regular expression: (0?[1-9]|[12][0-9]|3[01])[- /.](0?[1-9]|1[012])[- /.](19|20)?[0-9]{2}
Result: 09/12/2005
Example 8
Text: IP address Matches 0.0.0.0 through 255.255.255.255
Regular expression: ((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
Regular expression: (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
Result: 255.255.255.255
Example 9
Text: Number, floating point +255.255
Regular expression: [-+]?[0-9]+(\.[0-9]+)?
Result: +255.255
Example 10
Text: Date, Today is 2005-07-07
Regular expression: (19|20)\d{2}([_\s-\.\/]*)?(0[1-9]|1[012])([_\s-\.\/]*)?(0[1-9]|[12][0-9]|3[01])
Result: 2005-07-07
Example 11
Text: Time is 23:12:55
Regular expression: ([01][0-9]|2[0-3])([:_\s-\.\/]*)?([0-5][0-9])([:_\s-\.\/]*)?([0-5][0-9])?(.\d{3})?
Result: 23:12:55
Example 12
Text: Guid 12345678-ABCD-1234-ABCD-1234567890EF
Regular expression: [0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}
Result: 12345678-ABCD-1234-ABCD-1234567890EF
Example 13
Text: <a href='http://www.google.com/calendar/render?hl=ru&tab=wc' class=gb2>calendar</a>
Regular expression: href\s*=\s*'([^']*)'
Result: href='http://www.google.com/calendar/render?hl=ru&tab=wc'
Example 14
Text: Email is test@yahoo.com
Regular expression: [\w\.-]+@[\w-]+\.[\w\.-]+
Result: test@yahoo.com
Example 15
Text: <b>Hello</b>
Regular expression: <[^>]+>(.*)</[^>]+>
Result Group[1]: Hello
Example 16
Text: hello out there, how are you
Regular expression: h.*o
Result: hello out there, how are yo
Regular expression: h.*?o
Result: hello
Example 17
Text: Keyword = Value
Regular expression: (\w+)\s*=\s*(.*)\s*
Result: Keyword = Value
Example 18 (Parsing CSV Text)
Text: "earth",1,,"moon", 9.374
Regular expression: "([^"\\]*(\\.[^"\\]*)*)",?|([^,]+),?|,
Result:
"earth",
1,
,
"moon",
9.374
Example 19 (Get domain)
Text: http://domain.com/forums/AddPost.aspx?PostID=1
Regular expression: http://[^/]+/?
Result: http://domain.com/
Example 20 (Get complete url except last part file_name.ext)
Text: http://domain.com/forums/AddPost.aspx?PostID=1
Regular expression: http://[\w\.-]+.*/
Result: http://domain.com/forums/
Example 21 (Get some text blocks)
Text:
bar
Some lines of text
end bar
bar
Some lines of text 2
end bar
Regular expression: [^(bar|\r\n|end\s)].+
Result:
Some lines of text
Some lines of text 2
Example 22 (Get last folder name)
Text: C:\WINDOWS\system32\config\default.sav
Regular expression: [^\\]+(?=\\[^\\]+$)
Result: config
Example 23 (Get path)
Text: C:\WINDOWS\system32\config\default.sav
Regular expression: [a-zA-Z]:.*\\
Result: C:\WINDOWS\system32\config\
Example 24 (Get file name)
Text: C:\WINDOWS\system32\config\default.sav
Regular expression: ([^\\]+)$
Result: default.sav
Программы и сайты-онлайн для работы с регулярными выражениями
На сегодняшний день существует огромное количество всевозможных программ для создания и тестирования регулярных выражений. Почти все они отвечают необходимым минимальным требованиям: написать и протестировать регулярное выражение. Ну, и конечно же каждый пробовал написать что-то свое, свою программу-утилиту для построения и тестирования регулярных выражений (Regex). Вот еще одна из ряда подобных - может она будет удобна кому-то
Моя версия программы-утилиты для тестирования регулярных выражений
RegexView.exe (8.03)