英文:
regex for splitting a string while ignoring the brackets
问题
Sure, here's the translated content:
我想要通过空格字符来分割一个字符串,但忽略括号之间的空格。我使用的代码是:
String s = "hello (split this) string";
String reg = "(?<=([^\\(].*))( )(?=(.*[^\\)]))";
System.out.println(Arrays.toString(s.split(reg)));
我期望的输出是:
[hello , (split this) , string]
但我得到了这个错误:
Exception in thread "main" java.util.regex.PatternSyntaxException: Look-behind group does not have an obvious maximum length near index 12
(?<=([^(].))z(?=(.[^)]))
我需要一个正则表达式来获得期望的输出。所以,请有人帮忙。
英文:
I want to split a string with space-character but ignoring the space between two brackets.
The code i used is:
String s = "hello (split this) string";
String reg = "(?<=([^\\(].*))( )(?=(.*[^\\)]))";
System.out.println(Arrays.toString(s.split(reg));
My expected output is:
[hello , (split this) , string]
but i get this error
>Exception in thread "main" java.util.regex.PatternSyntaxException: Look-behind group does not have an obvious maximum length near index 12
(?<=([^(].))z(?=(.*[^)])) *
I need a regex to get the expected output.
So, somebody please help.
答案1
得分: 1
你可以使用以下正则表达式来实现你的需求:
[ ](?=[^\)]*?(?:\(|$))
以上正则表达式的解释:
>[ ]
- 表示一个空格字符。
>
> (?=[^\)]*?(?:\(|$))
- 表示正向先行断言,断言括号()
内的所有内容。
>
>(?:)
- 表示一个非捕获组。
>
> |
- 表示或操作。
>
> $
- 表示字符串的结尾。
你可以在这里找到上述正则表达式的演示。
在Java中的实现
import java.util.Arrays;
public class Main
{
public static void main(String[] args) {
String s = "hello (split this) string";
String reg = "[ ](?=[^\\)]*?(?:\\(|$))";
System.out.println(Arrays.toString(s.split(reg)));
}
}
// 输出: [hello, (split this), string]
你可以在这里找到上述实现。
英文:
You can use the below regex to achieve your requirement:
[ ](?=[^\)]*?(?:\(|$))
Explanation of the above regex:
>[ ]
- Represents a space character.
>
> (?=[^\)]*?(?:\(|$))
- Represents a positive look-ahead asserting everything inside of ()
.
>
>(?:)
- Represents a non-capturing group.
>
> |
- Represents alternation.
>
> $
- Represents the end of the test String.
You can find the demo of the above regex in here.
IMPLEMENTATION IN JAVA
import java.util.Arrays;
public class Main
{
public static void main(String[] args) {
String s = "hello (split this) string";
String reg = "[ ](?=[^\\)]*?(?:\\(|$))";
System.out.println(Arrays.toString(s.split(reg)));
}
}
// output: [hello, (split this), string]
You can find the above implementation here.
答案2
得分: 1
尝试使用 "(?:[^ (]+|(?>\\([^()]*\\))|\\()+(?=[ ]|$)"
注意:
- 用于匹配所有元素,而不是进行分割
- 将匹配不平衡的括号,并在括号上使用原子组,如
( kk hh )
英文:
Try "(?:[^ (]+|(?>\\([^()]*\\))|\\()+(?=[ ]|$)"
notes
- use to match all elements instead of split
- will match unbalanced parens and use a atomic group on paren like
( kk hh )
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论