gpt4 book ai didi

Java Regex 使用正则表达式保留预期字符串并删除其他字符串

转载 作者:行者123 更新时间:2023-12-01 19:52:33 25 4
gpt4 key购买 nike

我需要使用正则表达式的帮助。

我有一个包含字符和数字的字符串。例如:

str1="012345m67890man"

我只想保留子字符串“man”和数字。我不需要任何其他字母字符。

我正在使用以下正则表达式,但它也显示“m”字符。

str1 = str1.replaceAll("[^(man0-9)]", "");

实际输出:012345m67890man

预期输出:01234567890man

如果我的字符串包含除 man 之外的任何字母字符,我需要将其删除。

请帮我提建议。

最佳答案

您可以匹配并捕获man然后匹配除数字之外的所有字符并将其删除:

str1 = str1.replaceAll("(man)|[^0-9]", "$1");

请参阅regex demo

IDEONE Java demo :

String str1 = "012345m67890man";
str1 = str1.replaceAll("(man)|[^0-9]", "$1");
System.out.println(str1);

您可以阅读有关 Backreferences at regular-expressions.info 的更多信息:

If your regular expression has named or numbered capturing groups, then you can reinsert the text matched by any of those capturing groups in the replacement text. Your replacement text can reference as many groups as you like, and can even reference the same group more than once. This makes it possible to rearrange the text matched by a regular expression in many different ways. As a simple example, the regex \*(\w+)\* matches a single word between asterisks, storing the word in the first (and only) capturing group. The replacement text <b>\1</b> replaces each regex match with the text stored by the capturing group between bold tags.

在Java中,我们基本上使用$n反向引用语法,与 Perl 不同\n .

关于Java Regex 使用正则表达式保留预期字符串并删除其他字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35153334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com