Reputation: 8708
I'm making a code which takes a file and checks if it's a valid Java code, must be done using regexes.
I run over every line and checks if it end with ; or { or }. however, I can't seem to manage to limit it to only 1 occurence of it. i.e both
int i=0;
and
int i=0 ;;;;;;;
would pass.. The regex I'm using right now is
.+;{1}\\s*$
tried many other options, non seems to work. any help would be great! Thanks
Upvotes: 1
Views: 1874
Reputation: 13925
If you want to make sure, that there is only one semicolon in the whole row, then use:
^[^;]+;{1}\\s*$
This is not a proper check for a valid java source however.
Upvotes: 0
Reputation: 8986
Your problem is that the .
will also match a semicolon, so your expression will match all but the last semicolon as part of the .+
.
To avoid this, you could match any character except a semicolon by using [^;]
. i.e.
[^;]+;\\s*$
However, you should be aware that int i=0 ;;;;;;;;;
is perfectly valid Java code.
Upvotes: 2
Reputation: 94
This part of the regexp: .+
will match any character, including all but the last of your ;
's.
You need to exclude ;
from the first part of your regexp so that you can match "Anything but a ; followed by exactly one ;" (and once you get that working, you can expand your character class to capture also { and } if you wish)
HTH
Upvotes: 0