xHarbour Reference Documentation > Function Reference |
Searches a string using a regular expression
HB_RegEx( <cRegEx> , ; <cString> , ; [<lCaseSensitive>], ; [<lNewLine>] ) --> aMatches
The function returns an array filled with the found substrings matching the regular expression. If no match is found, the return value is NIL.
Function HB_RegEx() searches a character string using a regular expression and collects matching substrings in an array, which is returned. The first element of the returned array contains the whole match, while subsequent elements contain the portions of the whole match that comply with the regular expression. If the result in the first element does not match further, the returned array has one element only.
Note: the xHarbour Regular Expressions (RegEx) engine is using the PCRE implementation http://www.pcre.org/. Regular Expressions is a very powerful language specifically designed to analyze and match text patterns. The subject of RegEx is well beyond the scope of this documentation, and has been covered by many dedicated books. For a comprehensive description of RegEx in general, and PCRE in specific, please review http://www.pcre.org/.
A good introduction and tutorial on RegEx can also be found at http://www.regular-expressions.info/.
See also: | HAS, HB_AtX(), HB_RegExAll(), HB_RegExAtX(), HB_RegExComp(), HB_RegExSplit(), LIKE |
Category: | Character functions , Regular expressions , xHarbour extensions |
Source: | rtl\regex.c |
LIB: | xhb.lib |
DLL: | xhbdll.dll |
// The example extracts a time from a text string by searching // two pairs of digits separated by a colon. PROCEDURE Main LOCAL cRegEx := "[0-9]{2}:[0-9]{2}" LOCAL cText := "Departure is at 18:45h from London airport" LOCAL aResult aResult := HB_RegEx( cRegEx, cText ) AEval( aResult, {|c| QOut(c) } ) ** Output: // 18:45 RETURN
// The example matches an ISO formatted date string and displays // the whole match and sub-matches. PROCEDURE Main LOCAL cRegEx := "([0-9]{4})[-/]([0-9]{1,2})[-/]([0-9]{1,2})" LOCAL aDates := { "2006-9-28", ; "2006/10/1", ; "2006-123-1" } LOCAL cDate, aMatch FOR EACH cDate IN aDates ? ? "Matching: ", cDate aMatch := HB_RegEx( cRegEx, cDate ) IF aMatch == NIL ? "No match" ELSEIF Len( aMatch ) == 1 ? "Matched:", aMatch[1] ELSEIF Len( aMatch ) > 1 ? "Whole match:", aMatch[1] ? "Sub matches: " AEVal( aMatch,{|c| QQOut( '"'+ c +'" ') }, 2 ) ENDIF NEXT ** Output: // Matching: 2006-9-28 // Whole match: 2006-9-28 // Sub matches: "2006" "9" "28" // // Matching: 2006/10/1 // Whole match: 2006/10/1 // Sub matches: "2006" "10" "1" // // Matching: 2006-123-1 // No match RETURN
http://www.xHarbour.com