Jump to content

String matching: Difference between revisions

Emacs Lisp: Simplify example
(Emacs Lisp: Simplify example)
Line 1,743:
 
=={{header|Emacs Lisp}}==
<lang Lisp>(defun string-contains (needle haystack)
===With built-in functions===
(string-match (regexp-quote needle) haystack))
<lang Emacs Lisp>(defun match (word str)
(progn
(if (string-prefix-p word str)
(insert (format "%s found in beginning of: %s\n" word str) )
(insert (format "%s not found in beginning of: %s\n" word str) ))
(setq pos (string-match word str) )
(if pos
(insert (format "%s found at position %d in: %s\n" word pos str) )
(insert (format "%s not found in: %s\n" word str) ))
(if (string-suffix-p word str)
(insert (format "%s found in end of: %s\n" word str) )
(insert (format "%s not found in end of: %s\n" word str) ))))
(setq string "before center after")
(progn
(match "center" string)
(insert "\n")
(match "before" string)
(insert "\n")
(match "after" string) )
</lang>
<pre>center not found in beginning of: before center after
center found at position 7 in: before center after
center not found in end of: before center after
 
(string-prefix-p "before" found in beginning of: "before center after") ;=> t
(string-contains "before" found at position 0 in: "before center after") ;=> 0
(string-suffix-p "before" not found in end of: "before center after") ;=> nil
 
after(string-prefix-p not found in beginning of:"center" "before center after") ;=> nil
after(string-contains found at position 14 in:"center" "before center after") ;=> 7
after(string-suffix-p found in end of:"center" "before center after") ;=> nil
</pre>
===With regex===
<lang Emacs Lisp>(defun match (word str)
(progn
(setq regex (format "^%s.*$" word) )
(if (string-match regex str)
(insert (format "%s found in beginning of: %s\n" word str) )
(insert (format "%s not found in beginning of: %s\n" word str) ))
 
(string-prefix-p "after" "before center after") ;=> nil
(setq pos (string-match word str) )
(setq string-contains "after" "before center after") ;=> 14
 
(setq string-suffix-p "after" "before center after") ;=> t</lang>
(if pos
(insert (format "%s found at position %d in: %s\n" word pos str) )
(insert (format "%s not found in: %s\n" word str) ))
(setq regex (format "^.*%s$" word) )
(if (string-match regex str)
(insert (format "%s found in end of: %s\n" word str) )
(insert (format "%s not found in end of: %s\n" word str) ))))
 
(setq string "before center after")
 
(progn
(match "center" string)
(insert "\n")
(match "before" string)
(insert "\n")
(match "after" string) )
</lang>
<b>Output:</b>
<pre>Same output than above</pre>
 
=={{header|Erlang}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.