Reputation: 43
Hi I am writing regular expression:I need get info from this line
;row:1;field:2;name:3
My regular expression for this line is
.*(row:([0-9]{1,}))?;.*field:([0-9]{1,});.*name:([0-9]{1,});
But the problem that the word row is optional,I can also get the line without word row,but in this case my regular expressions does not work,how I can write it?
Thanks.
Upvotes: 0
Views: 57
Reputation: 99
If you are just trying to make the word row optional, you can surround it with parenthesis and use the question mark to say you want zero or one of the parenthesis contents. I have shown below:
(row:)?
This will find zero or one of "row:". I would recommend also adding the ?:
operator inside the open parenthesis if you are not trying to creating match groups:
(?:row:)?
Adding the ?:
operator tells the program that the parenthesis is not part of a match group, and you are using the parenthesis just to group the letters. So putting this into your regular expression looks like this:
.*((?:row:)?([0-9]{1,}))?;.*field:([0-9]{1,});.*name:([0-9]{1,});
If you want this applied to "field:" and "name:", then you would get this:
.*((?:row:)?([0-9]{1,}))?;.*(?:field:)?([0-9]{1,});.*(?:name:)?([0-9]{1,});
If you do not want the other parenthesis in your expression to create match groups, I would also change them. Also, to shorten the expression a little and make it cleaner I would change [0-9]
to \d
which means any digit, and I would replace {1,}
with +
which means "one or more", and remove the unnecessary parens which results in this:
.*(?:(?:row:)?\d+)?;.*(?:field:)?\d+;.*(?:name:)?\d+;
I'm not really sure that this is the final expression that you want, since your question was not very descriptive, but I have shown you how to find one or more of "row:" and clean up the expression a little without changing its meaning.
Upvotes: 1