Lex program to recognize a coefficient

I don’t know how to write the lex program that will recognize a “coefficient” like this:

%33.33%
%45.48%
etc

i wrote this in my lex file:

“[0-9][0-9]/.[0-9][0-9]” {printf(“coefficient”);}

it doesn’t work, anyone knows?

I’m reading this on a phone, so can’t verify, but a few hint questions jump to my attention:

  • where is the rule declaration?

  • what is the purpose of the slash in the regexp?

  • where is the regexp to match the percent symbols?

  • do you not want to print the matched value itself?

  • what do you want to do with characters that do not match any of your regexps?

No need to reply, if you just answer these to yourself - you’ll likely figure out what the problems are :slight_smile:

Maybe the code below (for OCamlLex) can serve as a starting point. If you were trying to solve the problem with regular expressions in an OCaml module, I misunderstood your question.

{
  (* vim: set ts=2 sw=2 et *)
  module L = Lexing

  exception Error
   
}

let digit   = ['0'-'9']
let coeff   = '%' digit+ '.' digit+ '%'

rule coeff = parse
| coeff as n eof   { n }
| _                { raise Error }

{

let coeff str = 
  try
    coeff (L.from_string str)
  with
    Error -> raise (Failure ("not a proper coeff: "^str))

let main () = 
  match Array.to_list Sys.argv with
  | [_;arg] ->
        Printf.printf "%s = %s\n" arg (coeff arg); 
        exit 0
  | _       -> exit 1

let () = main () 
}

Sorry, I put a question for lex programming in a OCaml forum my mistake
I found the solution it was:

%([0-9]* )|([0-9]* \ .[0-9]* )|(\ -[0-9]* )|(\ -[0-9]* \ .[0-9]* )%