I'm trying to make a program that, if given string with two dashes in it, returns the text between the first two dashes. If it does not have at least two dashes, it will return that it does not exist. Ex. I have a string
String s = "I AM -VERY- HUNGRY"
And I want my program to return VERY, which is between the two dashes. Here is my code so far
public static String middleText(String sentence)
{
int count = 0;
for (int i = 0; i < sentence.length(); i++)
{
if (sentence.charAt(i) == '-')
{
count++;
}
}
if (count >= 2)
{
return sentence.substring(sentence.indexOf("-") + 1);
}
else
{
return "DOES NOT EXIST";
}
}
However, this code does not produce my desired output. If I put the string I AM -VERY- HUNGRY
into this code, it would return VERY- HUNGRY
. How can I make it so it grabs the text only until the second dash?
You can use the following line:
return sentence.substring(sentence.indexOf("-")+1, sentence.lastIndexOf("-"));
Alternatively use the Regular Expression. See the link for the concrete Regex for this case at Regex101.
-(\w+)-
It matches the following:
\w+
means any letter at least one time +
.()
is capturing group-(\w+)-
captures one or more letters between -
charactersCombine Pattern
and Matcher
to achieve the result.
public static String middleText(String sentence) {
Pattern pattern = Pattern.compile("-(\w)-");
Matcher matcher = pattern.matcher(sentence);
if (matcher.find()) {
return matcher.group(1);
} else {
return "DOES NOT EXIST";
}
}
You can use Pattern and Matcher (java.util.regex) for this
String s = "I AM -VERY- HUNGRY";
Pattern patter = Pattern.compile("-(.*)-");
Matcher matcher = patter.matcher(s);
if (matcher.find()) {
System.out.println(matcher.group(1)); // VERY
} else {
System.out.println("no match");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With