4

I have these Strings:

"Turtle123456_fly.me"
"birdy_12345678_prd.tr"

I want the first words of each, ie:

Turtle
birdy

I tried this:

 Pattern p = Pattern.compile("//d");
 String[] items = p.split(String);

but of course it's wrong. I am not familiar with using Pattern.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
Moudiz
  • 7,211
  • 22
  • 78
  • 156
  • Possible duplicate of [How to extract a substring using regex](http://stackoverflow.com/questions/4662215/how-to-extract-a-substring-using-regex) – Stefano Zanini Mar 09 '17 at 16:34
  • Better you could have used string.tochararray() and check the ASCII code you will get your answer...! – Shailesh Mar 09 '17 at 16:35
  • @Shailesh Like [this example](https://www.mkyong.com/java/convert-string-to-char-array-in-java/) – Moudiz Mar 09 '17 at 16:38

3 Answers3

6

Replace the stuff you don't want with nothing:

String firstWord = str.replaceAll("[^a-zA-Z].*", "");

to leave only the part you want.

The regex [^a-zA-Z] means "not a letter", the everything from (and including) the first non-letter to the end is "removed".

See live demo.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
3
String s1 ="Turtle123456_fly.me";
String s2 ="birdy_12345678_prd.tr";

Pattern p = Pattern.compile("^([A-Za-z]+)[^A-Za-z]");
Matcher matcher = p.matcher(s1);

if (matcher.find()) {
    System.out.println(matcher.group(1));
}

Explanation: The first part ^([A-Za-z]+) is a group that captures all the letters anchored to the beginning of the input (using the ^ anchor). The second part [^A-Za-z] captures the first non-letter, and serves as a terminator for the letters sequence. Then all we have left to do is to fetch the group with index 1 (group 1 is what we have in the first parenthesis).

Alon Segal
  • 818
  • 9
  • 20
  • Please don't post code and tell "try this"... This community is about learning stuff, not about sharing source-code... Explain what are the main parts of the code, and what those parts of the code do, at the very least. – CosmicGiant Mar 09 '17 at 16:53
0

maybe you should try this \d+\w+.*

Just Me
  • 864
  • 2
  • 18
  • 28