[英]Regular Expression in Java. Splitting a string using pattern and matcher
我正在尝试获取字符串中的所有匹配组。 我的正则表达式是"(?<?')/|/(?!')
”。 我正在尝试使用正则表达式模式和匹配器拆分字符串。 字符串需要使用 / 来分割,但是 '/'(被 ' 包围)这需要被跳过。 例如"One/Two/Three'/'3/Four"
需要拆分为["One", "Two", "Three'/'3", "Four"]
但不使用.split 方法。
我目前是以下
// String to be scanned to find the pattern.
String line = "Test1/Test2/Tt";
String pattern = "(?<!')/|/(?!')";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.matches()) {
System.out.println("Found value: " + m.group(0) );
} else {
System.out.println("NO MATCH");
}
但它总是说“不匹配”。 我在哪里做错了? 以及如何解决这个问题?
提前致谢
要在不使用拆分的情况下获得匹配项,您可以使用
[^'/]+(?:'/'[^'/]*)*
解释
[^'/]+
匹配除'
或/
之外的任何字符 1+ 次(?:
非捕获组
'/'[^'/]*
匹配'/'
后跟可选匹配除'
或/
之外的任何字符)*
关闭组并选择性地重复它String regex = "[^'/]+(?:'/'[^'/]*)*";
String string = "One/Two/Three'/'3/Four";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println(matcher.group(0));
}
Output
One
Two
Three'/'3
Four
编辑
如果您don't
拆分,您也可以使用不匹配/
的模式,但仅在被单引号包围时
[^/]+(?:(?<=')/(?=')[^/]*)*
尝试这个。
String line = "One/Two/Three'/'3/Four";
Pattern pattern = Pattern.compile("('/'|[^/])+");
Matcher m = pattern.matcher(line);
while (m.find())
System.out.println(m.group());
output:
One
Two
Three'/'3
Four
尝试这样的事情:
String line = "One/Two/Three'/'3/Four";
String pattern = "([^/]+'/'\d)|[^/]+";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
boolean found = false;
while(m.find()) {
System.out.println("Found value: " + m.group() );
found = true;
}
if(!found) {
System.out.println("NO MATCH");
}
Output:
Found value: One
Found value: Two
Found value: Three'/'3
Found value: Four
这是匹配所有所需/
的简单模式,因此您可以按它们拆分:
(?<=[^'])\/(?=')|(?<=')\/(?=[^'])|(?<=[^'])\/(?=[^'])
逻辑如下:我们有4种情况:
/
被'
包围,即 `'/'
/
前面是'
,即'/
/
后跟'
,即/'
/
被'
以外的字符包围
您只想排除 1. 案例。 所以我们需要为三种情况编写正则表达式,所以我写了三个类似的正则表达式并使用了交替。
第一部分的解释(其他两个类推):
(?<=[^'])
- positiva lookbehind,断言前面的内容是不同的 frim '
(否定字符 class [^']
\/
- 匹配/
字面意思
(?=')
- positiva 前瞻,断言后面是'
\
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.