如何在 Java 中使用正则表达式拆分特殊字符
How to split special char with regex in Java
如果有以下字符串:
MAC 1 USD14,IPHONE4 1-2-3-4 USD22,USD44,USD66,USD88
然后我想生成以下输出:
1,1,2,3,4
我正在使用 (\bUSD\d{1,99})(\bMAC)(\bIPHONE\d)
拆分它,但它不起作用。
我该怎么办?
不要使用 split()
。使用 Pattern
和 Matcher
来提取字符串。会更容易。
public static void main(String[] args) {
String s = "MAC 1 USD14,IPHONE4 1-2-3-4 USD22,USD44,USD66,USD88<br>";
Pattern p = Pattern.compile("(?<=\s|-)\d(?=\s|-)"); // extract a single digit preceeded and suceeded by either a space or a `-`
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group());
}
}
O/P :
1
1
2
3
4
注意:Pattern.compile("\b\d\b");
也会给你同样的答案。
编辑:(?<=\s|-)\d(?=\s|-)"
:
(?<=\s|-) --> positive look-behind. Looks for a digit (\d) preceeded
by either a space or a - (i.e, dash).
(?=\s|-) --> positive look-ahead. Looks for a digit (\d) followed
by either a space or a - (i.e, dash).
请注意,后视/前瞻是 匹配的 但不是 捕获的
如果有以下字符串:
MAC 1 USD14,IPHONE4 1-2-3-4 USD22,USD44,USD66,USD88
然后我想生成以下输出:
1,1,2,3,4
我正在使用 (\bUSD\d{1,99})(\bMAC)(\bIPHONE\d)
拆分它,但它不起作用。
我该怎么办?
不要使用 split()
。使用 Pattern
和 Matcher
来提取字符串。会更容易。
public static void main(String[] args) {
String s = "MAC 1 USD14,IPHONE4 1-2-3-4 USD22,USD44,USD66,USD88<br>";
Pattern p = Pattern.compile("(?<=\s|-)\d(?=\s|-)"); // extract a single digit preceeded and suceeded by either a space or a `-`
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group());
}
}
O/P :
1
1
2
3
4
注意:Pattern.compile("\b\d\b");
也会给你同样的答案。
编辑:(?<=\s|-)\d(?=\s|-)"
:
(?<=\s|-) --> positive look-behind. Looks for a digit (\d) preceeded by either a space or a - (i.e, dash).
(?=\s|-) --> positive look-ahead. Looks for a digit (\d) followed by either a space or a - (i.e, dash).
请注意,后视/前瞻是 匹配的 但不是 捕获的