user1410081
user1410081

Reputation:

Java extract only first letters/characters from String

Hello guys I want to extract only first letters from this String:

  String str = "使 徒 行 傳 16:31 ERV-ZH";

I only want to get these characters:

  使 徒 行 傳

and not include

   ERV-ZH

Only the letters or characters before the numbers plus the colon.

Note that Chinese letters can also be English and other letters.

this is what I've tried:

str.split(" ")[0];

But I'm only getting the first letter. Do you have an idea how to achieve my requirement? Any help will be appreciated. Thanks.

NOTE:

Also, strings are dynamic so I only presented sample characters.

Upvotes: 0

Views: 123

Answers (3)

cнŝdk
cнŝdk

Reputation: 32145

You can use the following regex ^([\\D\\s]+), this is what you need:

  String str = "使 徒 行 傳 16:31 ERV-ZH";
  String pattern = "^([\\D\\s]+)";

  Pattern r = Pattern.compile(pattern);

  Matcher m = r.matcher(str);
  if (m.find( )) {
     System.out.println("Found value: " + m.group(0) );
  } else {
     System.out.println("NO MATCH");
  }
}

This is a live DEMO here.

In the following regex ^([\\D\\s]+):

  • ^ will match only in the begginnig.

  • \\D will avoid matching any number.

Note that this will be the case for any string.

Upvotes: 0

dotvav
dotvav

Reputation: 2848

If you don't always have a date pattern that can be used as a delimiter in the middle, and are looking for a more generic solution, you could go with this: str.replaceAll("[^\\p{L}\\s]+.*", "")

Upvotes: 0

SomeJavaGuy
SomeJavaGuy

Reputation: 7347

This should give you the desired output

String str = "使 徒 行 傳 16:31 ERV-ZH";

String[] test = str.split("\\d\\d:\\d\\d");

for (String s : test) {
    System.out.println(s);
}

The first element will be the part before the time and so on

Edit: if you are in need to be more dynamic for times like 6:31 or 16:6 then you could use this regex "\\d{1,2}:\\d{1,2}"

Upvotes: 3

Related Questions