简体   繁体   English

Java仅从字符串中提取首字母/字符

[英]Java extract only first letters/characters from String

Hello guys I want to extract only first letters from this String: 大家好,我只想从此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. 另外,字符串是动态的,因此我只介绍了示例字符。

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}" 编辑:如果您需要在6:3116:6类的时间内更加动态,则可以使用此正则表达式"\\\\d{1,2}:\\\\d{1,2}"

You can use the following regex ^([\\\\D\\\\s]+) , this is what you need: 您可以使用以下正则表达式^([\\\\D\\\\s]+) ,这是您需要的:

  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]+) : 在以下正则表达式^([\\\\D\\\\s]+)

  • ^ will match only in the begginnig. ^仅在begginnig中匹配。

  • \\\\D will avoid matching any number. \\\\D将避免匹配任何数字。

Note that this will be the case for any string. 请注意 ,任何字符串都是如此。

如果您并不总是将日期模式用作中间的定界符,并且正在寻找更通用的解决方案,则可以使用以下方法: str.replaceAll("[^\\\\p{L}\\\\s]+.*", "")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM