如何用Java符号'^'拆分Java中的字符串?

时间:2021-08-23 22:07:47

I am struggling with the string split method and the caret symbol (^) in java.

我正在努力使用java中的字符串拆分方法和插入符号(^)。

Input:

value1^value2^value3\^value3part2

Expected output:

[value1, value2, value3^value3part2]

Can anyone please provide a solution for this?

有谁能请为此提供解决方案?

I have tried multiple solutions but with no success.

我尝试了多种解决方案但没有成功。

Thank you.

1 个解决方案

#1


3  

Based on your comments it looks like you want to split only on ^ if it is not preceded by \. In that case you can use negative look-behind mechanism (?<!...) which tests if part which we are trying to match is not preceded by regex described in ....

根据您的评论,如果它没有以\开头,您似乎只想在^上拆分。在这种情况下,你可以使用负面的后视机制(?

In your case you can use it like:

在您的情况下,您可以使用它:

String[] values = yourLine.split("(?<!\\\\)\\^");

So you want to split

所以你想拆分

  • on ^ (we needed to escape it \\^ since ^ it is one of regex metacharacters),
  • on ^(我们需要将其转义为\\ ^,因为^它是正则表达式元字符之一),

  • which doesn't have \ before (?<!\\\\) - we needed to escape \ twice, once in regex, once in string literal.
  • 哪个没有\ before(?

#1


3  

Based on your comments it looks like you want to split only on ^ if it is not preceded by \. In that case you can use negative look-behind mechanism (?<!...) which tests if part which we are trying to match is not preceded by regex described in ....

根据您的评论,如果它没有以\开头,您似乎只想在^上拆分。在这种情况下,你可以使用负面的后视机制(?

In your case you can use it like:

在您的情况下,您可以使用它:

String[] values = yourLine.split("(?<!\\\\)\\^");

So you want to split

所以你想拆分

  • on ^ (we needed to escape it \\^ since ^ it is one of regex metacharacters),
  • on ^(我们需要将其转义为\\ ^,因为^它是正则表达式元字符之一),

  • which doesn't have \ before (?<!\\\\) - we needed to escape \ twice, once in regex, once in string literal.
  • 哪个没有\ before(?