Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex pattern not fit well for code like assignment

Tags:

regex

i am trying to use a regular expression to match expression like code assignment for example:

"k=++g677"
"k=--j77"
"k=++gfrf677frfr"

i've tried:

([a-zA-Z])([a-zA-Z]|\d)*[=][+][+]|[-][-]|[*][*]|[\/][\/]([\d]*|([a-zA-Z]([a-zA-Z]\d)*))

but it's seemds to match also things like

"k++"
"k=++@ff"

can u help?

like image 386
user10776203 Avatar asked Dec 08 '25 09:12

user10776203


1 Answers

You may use

^[a-zA-Z_][\da-zA-Z_]*=([+*\/-])\1[a-zA-Z_][\da-zA-Z_]*$

Or, if you need to capture each detail into a separate group:

^([a-zA-Z_][\da-zA-Z_]*)(=)(([+*\/-])\4)([a-zA-Z_][\da-zA-Z_]*)$

See this regex demo and its graph:

enter image description here

Details

  • ^ - start of string
  • [a-zA-Z_] - an uppercase ASCII letter or underscore
  • [a-zA-Z\d_]* - 0 or more alphanumerics / _ (replace with \w if it is not Unicode aware by default)
  • = - an equal sign
  • ([+*\/-])\1 - +, *, / or - and then exactly 1 the same char
  • [a-zA-Z_] - an ASCII letter or _
  • [a-zA-Z\d_]* - 0 or more alphanumerics / _ (replace with \w if it is not Unicode aware by default)
  • $ - end of string.
like image 124
Wiktor Stribiżew Avatar answered Dec 09 '25 22:12

Wiktor Stribiżew