1

嗨,我有一个字符串,想提取一个与正则表达式匹配的子字符串,我当前拥有的代码删除了我希望它成为唯一应该保留的部分的子字符串。

我有什么,这将其删除,我想保留它:

String ticketReference = "You have been assigned to the following Support Ticket: ST-00003 bla bla bla";

ticketReference =  ticketReference.replaceAll("'((ST-)[0-9]{5})", " ");

所需输出:“ST-00003”

提前感谢

4

2 回答 2

3

您可以使用捕获组来执行此操作,它们$n在 Java 中表示:

String ticketReference = "You have been assigned to the following Support Ticket: ST-00003 bla bla bla";
ticketReference =  ticketReference.replaceAll("^.*(ST-[0-9]{5}).*$", "$1");
于 2012-07-20T08:02:14.410 回答
0

replaceAll解决方案没有错误处理,因此如果未找到匹配项,则字符串保持不变。


这是使用Patternand的正确方法Matcher(在我看来更容易):

String stringToDecode = 
     "You have been assigned to the following Support Ticket: ST-00003 bla bla";

Matcher m = Pattern.compile("ST-[0-9]{5}").matcher(stringToDecode);

if (!m.find())
    throw new CouldNotFindTicketException(stringToDecode);

String ticketReference = m.group();
//...
于 2012-07-20T09:23:29.153 回答