Reputation: 2881
I want to match a string starting with capital letter and have length < 70.
I tried this regex ([A-Z][a-zA-Z\s\/\-]*\:?\'?)
to check if the string starts with capital letter. It is working fine. But to check length, I changed to (([A-Z][a-zA-Z\s\/\-]*\:?\'?){4,70})
and it is not working.
Though, I can check the length using length()
method of string in if
statement. Doing so would make if
statement lengthy. I want to combine length checking in regex itself. I think it can be done in regex, but I am not sure how.
Update(Forgot to mention): String can have either of two symbol- :,' and only one of two will be there for either zero or one time in the string.
E.g : Acceptable String : Looking forwards to an opportunity
, WORK EXPERIENCE:
, WORK EXPERIENCE-
, India's Prime Minister
UnAcceptable String : Work Experience::
, Manager's Educational Qualification-
, work experience:
, Education - 2014 - 2017
, Education (Graduation)
Kindly help me.
Thanks in advance.
Upvotes: 1
Views: 2290
Reputation: 43169
You'll certainly need anchors and lookarounds
(?=^[^-':\n]*[-':]{0,1}[^-':\n]*$)^[A-Z][-':\w ]{4,70}$
Thus, a string between 5-71 characters will be matched, see a demo on regex101.com. Additionally, it checks for the presence of zero or one of your Special characters (with the help of lookarounds, that is).
Upvotes: 3
Reputation: 131456
Specify a lookaround assertion at the start of the regex that asserts that it may contain between 4 and 70 characters :
(?=.{4,70}$)
You would write so :
String regex = "(?=.{4,70}$)[A-Z][a-zA-Z\\s\\/\\-]*\\:?\\'?";
Upvotes: 1
Reputation: 35038
I would add ^
and $
to your regex:
^[A-Z].{,69}$
should work. This means:
^
beginning of the string[A-Z]
any capital character (in English anyway).{0,69}
up to 69 other characters$
end of the stringfor a total length of up to 70 characters...
Upvotes: 3
Reputation: 44854
why would the if
statement be lengthy?
String str = "Scary";
if (str.length() < 70 && str.charAt(0) >= 'A') {
}
Upvotes: 1