Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java正则表达式子字符串_Java_Regex_String - Fatal编程技术网

Java正则表达式子字符串

Java正则表达式子字符串,java,regex,string,Java,Regex,String,嗨,我有一个字符串,想提取一个子字符串匹配正则表达式我目前的代码删除子字符串我希望它是唯一应该保留的部分 我所拥有的,这会移除它,我想保留它: String ticketReference = "You have been assigned to the following Support Ticket: ST-00003 bla bla bla"; ticketReference = ticketReference.replaceAll("'((ST-)[0-9]{5})", " ");

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

我所拥有的,这会移除它,我想保留它:

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”


Thanx预先

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

String ticketReference = "You have been assigned to the following Support Ticket: ST-00003 bla bla bla";
ticketReference =  ticketReference.replaceAll("^.*(ST-[0-9]{5}).*$", "$1");

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


下面是一个使用
模式
匹配器
的正确方法(在我看来,这要容易得多):


如果ST-00003之后没有换行符,效果很好。如果有换行符,如何使它仍然返回正确?谢谢你,没关系,thaks
code-ticketReference.replaceAll(“^.*(ST-[0-9]{5}[\\n]*)。$”,“$1”)
通过设置
模式,也可以使
匹配
\n
。DOTALL
标志:
“(?s^.*(ST-[0-9]{5})。*$”
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();
//...