Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grab the string between the first and last occurrence of a hyphen

Tags:

java

string

regex

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?

like image 547
redbull_nowings Avatar asked Dec 10 '22 14:12

redbull_nowings


2 Answers

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 - characters

Combine 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";
    }
}
like image 197
Nikolas Charalambidis Avatar answered May 13 '23 15:05

Nikolas Charalambidis


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");
}
like image 25
baao Avatar answered May 13 '23 15:05

baao