Reputation: 35
Could you please let me know how to check whether the line ending with multiple underscores.
am able to check whether string ends with underscore but not able to get the count of number of underscores at the end of line.
Based on the underscores count i need to assign localNumberOfColumns
if(line.endsWith("_")){
localNumberOfColumns=NumberOfColumns-1;
}else{
localNumberOfColumns=NumberOfColumns;
}
Upvotes: 2
Views: 295
Reputation: 97322
You can split()
of all final underscores, and then compare the length of the original input with the length of the input with the underscores removed:
String s = "abc123___";
String sWithoutUnderscores = s.split("_*$")[0];
int numberOfUnderscores = s.length() - sWithoutUnderscores.length();
Update
As pointed out in the comments, above solution fails for cases where the string contains only underscores. If that is a possibility in your domain, consider using Java's pattern matching utilities:
String s = "abc123___";
Matcher matcher = Pattern.compile("_*$").matcher(s);
int numberOfUnderscores = matcher.find() ? matcher.group().length() : 0;
Upvotes: 2
Reputation: 522501
What first came to mind for me was simply comparing the length of your input string against the length of your string with all final underscores removed.
String threeUS = "abc123___";
int numUS = threeUS.length() - threeUS.replaceAll("(?:_)*$", "").length();
System.out.println("Number of underscores: " + numUS);
Output:
Number of underscores: 3
Demo here:
Upvotes: 2