Erlang/OTP Forums

Author Message

<  Erlang  ~  regexp with \.

5hundy
Posted: Tue Oct 23, 2007 8:39 am Reply with quote
User Joined: 14 Oct 2007 Posts: 17
I want the first part of a string before the "."

For example I want "foo" from "foo.abc"

in ruby I would do:
Code:
"foo.abc".gsub(/\..*/,'')


in erlang I tried:
Code:
regexp:sub("foo.abc", "\..*", "").


but I get an empty list. In many other cases it seems that \. does not work properly. Is this a bug? How should I split my string?
View user's profile Send private message
hao
Posted: Tue Oct 23, 2007 1:10 pm Reply with quote
User Joined: 20 Aug 2007 Posts: 18 Location: Uppsala, Sweden
Hi, 5hundy,

Don't worry, '\.' is not a bug. It seems that you misused it. Please refer to: http://www.erlang.org//doc/man/regexp.html
At the end of this document about regexp module, you can find out some regular expression rules. Two of them need to be pay attention to:

Quote:
\c matches the escape sequence or literal character c.

. matches any character.


So '\.' could not be able to represent '.' in the string. I think the code should be modified to:

Code:
43> regexp:sub("foo.abc", "[.].*", "").
{ok,"foo",1}

44> regexp:sub("foo.abc123!@#$%^&*()_+=<>|", "[.].*", "").
{ok,"foo",1}


If you are not compulsory to use regexp module to achieve it, you can also choose string module. Code can be looked like the followings:

Code:
49> string:left("foo.abc",(string:chr("foo.abc", $.)-1)).
"foo"


or

Code:
51> string:tokens("foo.abc", ".").
["foo","abc"]
View user's profile Send private message Send e-mail MSN Messenger
5hundy
Posted: Tue Oct 23, 2007 7:39 pm Reply with quote
User Joined: 14 Oct 2007 Posts: 17
Got it. Yeah, I saw those lines in the man page but I had trouble reconciling that with what I know of regular expressions in other environments.

Thanks for the help! Very Happy
View user's profile Send private message
hao
Posted: Tue Oct 23, 2007 9:45 pm Reply with quote
User Joined: 20 Aug 2007 Posts: 18 Location: Uppsala, Sweden
With pleasure. Glad to be helpful. Smile
View user's profile Send private message Send e-mail MSN Messenger

Display posts from previous:  

All times are GMT
Page 1 of 1
This forum is locked: you cannot post, reply to, or edit topics.

Jump to:  

You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You cannot download files in this forum