tags:

views:

111

answers:

3

Hi, I want to take the first comma seperated value from that string.

"Lines.No;StartPos=3;RightAligned;MaxLength =2"

I used "\b.*\;" regex to take "Lines.No". But the result is

"Lines.No;StartPos=3;RightAligned;"

thanks.

+4  A: 

First, anchor the search at the start of the string. Then use a lazy quantifier: ^\b.*?; or a negated character class: ^\b[^;];

But careful: Could semicolons appear in your CSV fields (in quoted strings)? If so, regexes can still be made to work, but will be a lot more complicated - a CSV parser would be much better.

Tim Pietzcker
thanks for your quick response. But the result is like that;Lines.No;\nStartPos=3;\nRightAligned;
mkus
OK, you probably need to make sure that the regex engine is anchored at the beginning of the string. I have edited my answer.
Tim Pietzcker
+2  A: 

I know you are looking fore a regex, but if you have delimited string, use your favourite language's split() function, eg in Python

>>> s="Lines.No;StartPos=3;RightAligned;MaxLength =2"
>>> s.split(";")[0]
'Lines.No'

Much simpler than regex. Similarly, explode() in PHP, split() in Perl, Split() in C# , etc

ghostdog74
+1. I think using `split` in this case makes the code a little cleaner. Even simple regular expressions make the code a little more obtuse, and I'd much rather see operations expressed in more explicit constructs if possible. Regex has its place, but not as a substitute for a simple split().
Seth Petry-Johnson
+1  A: 

You could do this way too, in python

>>> x="Lines.No;StartPos=3;RightAligned;MaxLength =2"
>>> x[:x.find(";")]
'Lines.No'
S.Mark