Regular Expression or Regex

Issues and Discussions related to Harbour

Moderator: Rathinagiri

User avatar
hmgchang
Posts: 273
Joined: Tue Aug 13, 2013 4:46 am
Location: Indonesia

Regular Expression or Regex

Post by hmgchang »

Hello Masters,
I was looked into the check.hb files and came across these lines,

FOR EACH match IN hb_regexAll( "([A-Za-z] |[^A-Za-z_:]|^)([A-Za-z_][A-Za-z0-9_]+\()", cFileStripped,,,,, .F. )
IF Len( match[ 2 ][ _MATCH_cStr ] ) != 2 .OR. !( Left( match[ 2 ][ _MATCH_cStr ], 1 ) $ "D" /* "METHOD" */ )
cProper := ProperCase( hAll, hb_StrShrink( match[ 3 ][ _MATCH_cStr ] ) ) + "("
IF !( cProper == match[ 3 ][ _MATCH_cStr ] ) .AND. ;
!( Upper( cProper ) == Upper( "FILE(" ) ) .AND. ; /* interacts with "file(s)" text */
!( Upper( cProper ) == Upper( "TOKEN(" ) ) .AND. ; /* interacts with "token(s)" text */
!( Upper( cProper ) == Upper( "INT(" ) ) .AND. ; /* interacts with SQL statements */
( ! lInCommentOnly .OR. !( "|" + Lower( cProper ) + "|" $ Lower( "|Max(|Min(|FOpen(|Abs(|Log10(|GetEnv(|Sqrt(|Rand(|IsDigit(|IsAlpha(|" ) ) )
cFile := Left( cFile, match[ 3 ][ _MATCH_nStart ] - 1 ) + cProper + SubStr( cFile, match[ 3 ][ _MATCH_nEnd ] + 1 )
IF lVerbose
OutStd( cFileName, match[ 3 ][ _MATCH_cStr ], cProper, "|" + match[ 1 ][ _MATCH_cStr ] + "|" + hb_eol() )
ENDIF
nChanged++
ENDIF
ENDIF
NEXT

I tried to figure out how the Regex works, but not easy. Can you pls give me some very basic understanding of Regular Expression and the usage ?
Thank you in advance !
Just Hmg It !
User avatar
esgici
Posts: 4543
Joined: Wed Jul 30, 2008 9:17 pm
DBs Used: DBF
Location: iskenderun / Turkiye
Contact:

Re: Regular Expression or Regex

Post by esgici »

Hi Chang
hmgchang wrote: I tried to figure out how the Regex works, but not easy. Can you pls give me some very basic understanding of Regular Expression and the usage ?
You may find some basic info about regular expression here.

For Harbour specific subject asking to Harbour Users Group or following Harbour Developers Group may be more useful.

Happy HMG'ing :D
Viva INTERNATIONAL HMG :D
User avatar
Amarante
Posts: 182
Joined: Fri Apr 27, 2012 9:44 pm
DBs Used: DBF, MySQL, MariaDB, SQLite, PostgreSQL
Location: Araruama-RJ, Brazil

Re: Regular Expression or Regex

Post by Amarante »

Below an example of the use of Regular Expression:

Code: Select all

*****************************************************************************
FUNCTION Swap_RegExp( cString, cExpRegular, cSwap )
* Parameters:
* cString      <expC> - string with data
* cExpRegular  <expC> - string with regular expression to find
* cSwap        [expC] - string to change (default SPACE( 1 ) )
* Return:
* expC - cString changed
*****************************************************************************
LOCAL	aFound
IF cSwap = NIL
  cSwap := SPACE( 1 )
ENDIF
cExpRegular := HB_RegexComp( cExpRegular )
DO WHILE .NOT. EMPTY( aFound := HB_Regex( cExpRegular, cString ) )
  cString := aFound[ 2 ] + cSwap + aFound[ LEN( aFound ) ]
ENDDO
RETURN cString
User avatar
danielmaximiliano
Posts: 2612
Joined: Fri Apr 09, 2010 4:53 pm
Location: Argentina
Contact:

Re: Regular Expression or Regex

Post by danielmaximiliano »

Gracias por compartir Amarante
*´¨)
¸.·´¸.·*´¨) ¸.·*¨)
(¸.·´. (¸.·` *
.·`. Harbour/HMG : It's magic !
(¸.·``··*

Saludos / Regards
DaNiElMaXiMiLiAnO

Whatsapp. := +54901169026142
Telegram Name := DaNiElMaXiMiLiAnO
User avatar
esgici
Posts: 4543
Joined: Wed Jul 30, 2008 9:17 pm
DBs Used: DBF
Location: iskenderun / Turkiye
Contact:

Re: Regular Expression or Regex

Post by esgici »

Hi Amarate
Amarante wrote:Below an example of the use of Regular Expression:
Thank to share, but;

Is this a "working" sample ?

fe

Code: Select all

LOCAL   aFound
...
  cString := aFound[ 2 ] ...    <- without declared aFound is an array

is this legal ?

And, we need a sample statement to call / apply this function for understanding the subject,

by see a regular expression is similar to what ?

Happy HMG :D
Viva INTERNATIONAL HMG :D
User avatar
Amarante
Posts: 182
Joined: Fri Apr 27, 2012 9:44 pm
DBs Used: DBF, MySQL, MariaDB, SQLite, PostgreSQL
Location: Araruama-RJ, Brazil

Re: Regular Expression or Regex

Post by Amarante »

esgici,
You were correct. Inadvertently I copied a routine part of my use and had not verified their operation. Follows, for those interested, the routine corrected and examples of using regular expressions.
hugs

Code: Select all

PROCEDURE MAIN()
LOCAL xRegex
LOCAL aMatch
LOCAL cStr := "This Text +Plus Date [1962-11-20] is A.3265-5"


// Example of using regular expression:
*------------------------------------------------------------
* checks if a text contains YYYY-MM-DD 
*------------------------------------------------------------
xRegex := HB_RegexComp( "([0-9]{4}[-][0-9]{2}[-][0-9]{2})" )
aMatch := HB_Regex( xRegex, cStr )
*------------------------------------------------------------
* Found
*------------------------------------------------------------
IF .NOT. EMPTY( aMatch )
  MsgInfo( aMatch[ 1 ] )
ENDIF


// Example of using Swap_RegExp function:
*------------------------------------------------------------
* regular expression (*)
*------------------------------------------------------------
cStr := Swap_RegExp( cStr, "([0-9]{4}[-][0-9]{2}[-][0-9]{2})", "Secret" )
MsgInfo( cStr )


*****************************************************************************
FUNCTION Swap_RegExp( cString, cExpRegular, cSwap )
* Parameters:
* cString      <expC> - string with data
* cExpRegular  <expC> - string with regular expression to find
* cSwap        [expC] - string to change (default SPACE( 1 ) )
* Return:
* expC - cString changed
*****************************************************************************
LOCAL   aFound
IF cSwap = NIL
  cSwap := SPACE( 1 )
ENDIF
cExpRegular := HB_RegexComp( cExpRegular )
IF .NOT. EMPTY( aFound := HB_Regex( cExpRegular, cString ) )
  cString := STRTRAN( cString, aFound[ 2 ], cSwap )
ENDIF
RETURN cString
Attachments
Samples_RegExp.rar
(25.55 KiB) Downloaded 343 times
Javier Tovar
Posts: 1275
Joined: Tue Sep 03, 2013 4:22 am
Location: Tecámac, México

Re: Regular Expression or Regex

Post by Javier Tovar »

No entiendo bien esto de expresiones reguleres, a que se refieren?.

Veo en los ejemplos que hay "Say", esto es en modo consola solamente?

Saludos

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

I do not understand this in reguleres expressions that refer to?.

I see in the examples that there is "Say" that is only in console mode?

regards
User avatar
Amarante
Posts: 182
Joined: Fri Apr 27, 2012 9:44 pm
DBs Used: DBF, MySQL, MariaDB, SQLite, PostgreSQL
Location: Araruama-RJ, Brazil

Re: Regular Expression or Regex

Post by Amarante »

Javier Tovar wrote:No entiendo bien esto de expresiones reguleres, a que se refieren?.

Veo en los ejemplos que hay "Say", esto es en modo consola solamente?

Saludos

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

I do not understand this in reguleres expressions that refer to?.

I see in the examples that there is "Say" that is only in console mode?

regards
Javier,
Examples are pure Harbour, so the use of SAY to display the result.
A regular expression in Computing, sets a standard to be used to find or replace words or groups of words. It is an accurate way to make certain portions of the search text.

For example, if the set of words is {wing, car, garden, eggs, ground} and regular expression search for a pattern rr, get the words car and land.
There are different formats to set up regular expressions, but with some general notions is possible to understand much of the expressions. Source: Wikipedia - Regular Expression

Read more at the Net Workshop: http://www.oficinadanet.com.br/artigo/p ... -regulares" onclick="window.open(this.href);return false;

Hope this helps.
hugs
----
Javier,
Los ejemplos están em Harbour, por lo que el uso de SAY es para mostrar el resultado.
Una expresión regular en Informática, establece un estándar que se utiliza para buscar o reemplazar palabras o grupos de palabras. Es una forma precisa para que ciertas partes del texto de búsqueda.

Por ejemplo, si el conjunto de palabras es {ala, coche, jardín, huevos, tierra} y búsqueda de expresiones regulares para un rr patrón, consiga la palabra coche y la tierra.
Existen diferentes formatos para crear expresiones regulares, pero con algunas nociones generales es posible entender gran parte de las expresiones. Fuente: Wikipedia - Expresión Regular

Ver más en el Taller neto: http://www.oficinadanet.com.br/artigo/p ... -regulares" onclick="window.open(this.href);return false;

Espero que esto ayude.
Abrazos
Javier Tovar
Posts: 1275
Joined: Tue Sep 03, 2013 4:22 am
Location: Tecámac, México

Re: Regular Expression or Regex

Post by Javier Tovar »

Muchas gracias por la información.

Saludos
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Thank you very much for the information.

regards
User avatar
serge_girard
Posts: 3165
Joined: Sun Nov 25, 2012 2:44 pm
DBs Used: 1 MySQL - MariaDB
2 DBF
Location: Belgium
Contact:

Re: Regular Expression or Regex

Post by serge_girard »

Hi All,

Regex can also be used in testing emailadresses:

Code: Select all

* checks if a text is a valid emailadres
cStr1 := "sg@host.com"	// VALID
cStr2 := "sg#host.com"	// INVALID

IF Is_Valid_Emailaddress(cStr1)   
	MsgInfo( cStr1  + ' is a VALID emailadres ', 'OK'  )
ELSE
   MsgInfo( cStr1  + ' is an invalid emailadres !!', 'NOK' )
ENDIF


IF Is_Valid_Emailaddress(cStr2)   
	MsgInfo( cStr2  + ' is a VALID emailadres ', 'OK'  )
ELSE
   MsgInfo( cStr2  + ' is an invalid emailadres !!', 'NOK' )
ENDIF

Function Is_Valid_Emailaddress(cStr)
/**********************************/
xRegex := HB_RegexComp( "([_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6})" )
aMatch := HB_Regex( xRegex, cStr  )
IF .NOT. EMPTY( aMatch )
   RETURN .T. // valid emailadres
ELSE
   RETURN .F. // invalid emailadres
ENDIF
It has not been tested extensively so I'm not sure if it is 100% OK.

Greetings,

Serge
There's nothing you can do that can't be done...
Post Reply