简体   繁体   English

在Java中分割包含(

[英]Split a string in Java containing (

I am trying to split a string in Java. 我正在尝试在Java中拆分字符串。

For example 例如

Hello (1234)

The part after ( must not be included in the string. I am expecting the following: 后面的部分(不得包含在字符串中。我期望以下内容:

Hello

How would you do it? 你会怎么做?

Just split according to 只是根据

  • zero or more spaces. 零个或多个空格。
  • And the following ( character. 及以下(字符。
  • Then get the value from index 0 of splitted parts. 然后从分割零件的索引0中获取值。

     "Hello (1234)".split("\\\\s*\\\\(")[0]; 

or 要么

    "Hello (1234)".split("\\s+")[0];

You can replace the contents in the parenthesis by nothing. 您不能用括号替换括号中的内容。

    String str = "Hello(1234)";
    String result = str.replaceAll("\\(.*\\)", "");
    System.out.println(result);

You mention split operation in the question, but you say 您在问题中提到了拆分操作,但您说

The part after ( must not be included in the string. I am expecting the following: 后面的部分(不得包含在字符串中。我期望以下内容:

So I'm assuming you are discarding the (1234) ? 所以我假设您正在丢弃(1234) If you need to save it, consider the other answer (using split ) 如果需要保存,请考虑其他答案(使用split

You may try the following regex 您可以尝试以下正则表达式

  String[] split = "Hello (1234)".split("\\s*\\([\\d]*\\)*");
  System.out.println(split[0]);

\\\\s* space may be ignored \\\\ s *空格可能会被忽略
\\\\( ( or left parenthesis has special meaning in regex so \\\\( means only ( \\\\((或左括号在正则表达式中具有特殊含义,因此\\\\(仅表示(
Same is the case with ) or right parenthesis \\\\) )或右括号\\\\)也是如此
\\\\d* digits may be present \\\\ d *数字可能存在
You may use + instead of * if that character is present at-least once 如果该字符至少出现一次,则可以使用+代替*

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

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