What is regex for the end of string in Julia?

What is regular expression for the final end of string in Julia?

It’s $, just like in all standard regex.

julia> x = "abc1 abc2 abc3";

julia> m = match(r"[a-z]*[1-9]$", x)
RegexMatch("abc3")
2 Likes

If you don’t know what is at the end of string then how will you find end ?

julia> x=" Raman Kumar"
" Raman Kumar"

julia> m = match(r"[a-z]*[1-9]$", x)

julia> 

Technically, $ matches the end of a string not including a trailing newline.

julia> contains("foobar", r"r$")
true

julia> contains("foobar\n", r"r$") # ignores the trailing newline
true

julia> contains("foobar ", r"r$") # but doesn't ignore other whitespace
false

To match only the end, not ignoring a newline, use \z:

julia> contains("foobar", r"r\z")
true

julia> contains("foobar\n", r"r\z")
false
1 Like

If i don’t know what is at end of string then what should i use ? r".$"

julia> x=" Raman Kumar yadav"
" Raman Kumar yadav"

julia> m =match(r"r$",x)

julia> m =match(r"v$",x)
RegexMatch("v")

julia> m =match(r".$",x)
RegexMatch("v")

julia> m =match(r".{5}$",x)
RegexMatch("yadav")

julia> 

This regular expression does not match your string x because r"[a-z]*[1-9]$" only matches a string that ends with a number 1-9. That’s why it returns m === nothing.

If you just want to know the last character of the string, don’t use a regex at all — you can just use x[end]:

julia> x[end]
'r': ASCII/Unicode U+0072 (category Ll: Letter, lowercase)

r".$" Will that be good regular expression for final end of the string ?

 r".$"

regular expression is for finding pattern, if there is a pattern only happens at the of a string that you know, you would use regex to find, and to match.

if you want to find the final end “character” of the string, you index it like mentioned.
if you want to find the final end “token” (separated by white space in most language), you can use this r"\s(\w+)$", or just last(split(x))

2 Likes