I want to extract the return value from a given text that represents a method.
for example:
g: x and: y
Transcript show: x; show: y.
^x+y.
so to solve I used the regular expression:
\^\s*(\w+.*).
when I run this on some regex websites it seems to work and do what I want, for example : https://regex101.com/
but when I run the following program it seems that squeak returns nil
to it (can't find a match). I suspect that is because I am using the character ^
.
but I escaped that character so I have no idea why that is failing to work.
the code I used to test it:
|aString regexObj |
aString := 'g: x and: y
Transcript show: x; show: y.
^x+y.'.
regexObj := '\^\s*(\w+.*).' asRegex.
regexObj matches: aString.
returnedType:= (regexObj subexpression:2).
Transcript show: returnedType.
anyone knows why, and how to solve it?
Thanks.
You need to replace the method from matches
to search
. See 139.6. Matching:
matches: aString
— true if the whole argument string (aString
) matches.
and
search: aString
— Search the string for the first occurrence of a matching substring. Note that the first two methods only try matching from the very beginning of the string. Using the above example with a matcher fora+
, this method would answer success given a string'baaa'
, while the previous two would fail.
The first two methods refers to matches
(requiring a full string match) and matchesPrefix
(that anchors the match at the start of the input string). The search
allows matching the pattern anywhere inside the string.
A note on your regex: the final .
is not escaped and matches any non-line break char. You should escape it to match a literal dot:
'\^\s*(\w.*)\.'
See the regex demo.
Also, \s
match match across lines. If you do not want it, replace \s
with \h
(a PCRE pattern that matches only horizontal whitespaces). Watch out for the .*
pattern: it will match any 0+ chars other than line break chars, as many as possible, so, it will match up to the last .
on a matching line.