[英]How do I write a regex that matches a certain character within brackets?
So I have a string that's like this,所以我有一个这样的字符串,
(name|address)
([name|address])
[name|address]
So I want to check for '|'所以我想检查'|' character and ignore if it's in the brackets like I have shown in the example.
字符并忽略它是否在我在示例中显示的括号中。
I have added this regex but it's not capturing all scenarios that I have described.我已经添加了这个正则表达式,但它没有捕捉到我描述的所有场景。
\\|(?![^(]*\\))
Edit:编辑:
If I have string like this,如果我有这样的字符串,
|Hello all, | morning [name|address] |
Then I am breaking the string by |
然后我用
|
断开字符串character.特点。 But I don't want to consider
|
但我不想考虑
|
character which are inside the brackets while breaking the string.破坏字符串时括号内的字符。
You can use您可以使用
import java.util.*;
import java.util.regex.*;
class Test
{
public static void main (String[] args) throws java.lang.Exception
{
String s = "|Hello all, | morning [name|address] |";
Pattern pattern = Pattern.compile("(?:\\([^()]*\\)|\\[[^\\]\\[]*]|[^|])+");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
System.out.println(matcher.group().trim());
}
}
}
See the regex demo and the Java demo .请参阅正则表达式演示和Java 演示。
Details :详情:
(?:
- start of a non-capturing group: (?:
- 非捕获组的开始:
\([^()]*\)|
- (
, zero or more chars other than (
and )
, and then a )
char, or (
,除(
和)
之外的零个或多个字符,然后是一个)
字符,或\[[^\]\[]*]|
- [
, zero or more chars other than a [
or ]
char, and then a ]
char, or [
,除[
或]
字符之外的零个或多个字符,然后是]
字符,或[^|]
- any single char other than a pipe char [^|]
- 除管道字符外的任何单个字符)+
- end of the group, repeat one or more times. )+
- 小组结束,重复一次或多次。 Note that in Android, Java, ICU regex flavors, both [
and ]
must be escaped inside character classes.请注意,在 Android、Java、ICU 正则表达式风格中,
[
和]
都必须在字符类中进行转义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.