从主字符串中提取子字符串在Java中

huangapple go评论73阅读模式
英文:

Extract substrings from main string in Java

问题

我正在尝试从主字符串中提取特定部分的字符串。例如,我有以下字符串。

A receipt is sent to abc@gmail.com. Please keep it for your own reference.

我只想提取

abc@gmail.com

从字符串中。

根据我找到的解决方案,它利用了从字符串开头到字符串中电子邮件部分开头的索引的“count”,以及从电子邮件部分之后到字符串结尾的索引。然而,我认为这仅在电子邮件中的字符数是固定的情况下有效。不幸的是,在我的情况下,电子邮件是动态的,这意味着字符串保持不变,只有用户输入的电子邮件会填充到字符串中。请给予建议。

英文:

I am trying to extract a certain portion of string from a main string. For example, I have the following string.

A receipt is sent to abc@gmail.com. Please keep it for your own reference.

I just want to extract

abc@gmail.com

from the string.

From the solutions I found, it utlises the "count" of index from beginning of the String up to the beginning of the email section of the string, and from after the email section to the end of the string. However, I think this only works if the number of characters in the email is fixed. Unfortunately, mine here is dynamic, which means the string remains the same except that the email will be populated with the email that the user keyed in. Kindly advise.

答案1

得分: 1

"Assuming you are starting with this input string and just want to extract a single email address, you may consider using String#replaceAll for a one-liner option:

String input = "A receipt is sent to abc@gmail.com. Please keep it for your own reference.";
String email = input.replaceAll(".*\\b(\\w\\S*@\\S*\\w)\\b.*", "$1");
System.out.println(email);

This prints:

abc@gmail.com
```"

<details>
<summary>英文:</summary>

Assuming you are starting with this input string and just want to extract a single email address, you may consider using `String#replaceAll` for a one-liner option:

    String input = &quot;A receipt is sent to abc@gmail.com. Please keep it for your own reference.&quot;;
    String email = input.replaceAll(&quot;.*\\b(\\w\\S*@\\S*\\w)\\b.*&quot;, &quot;$1&quot;);
    System.out.println(email);

This prints:

    abc@gmail.com

</details>



huangapple
  • 本文由 发表于 2020年8月6日 12:05:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63276694.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定