作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试将用量
中的非英文文本匹配到name=用量
以及将用量2
匹配到name=用量
和 number=2
。我在 RegexPlanet 上尝试了 (\p{L}+)(\d*)
,它可以工作,但是当它在 java 中运行时,无法将 2
取出第二个测试用例。
代码如下:
String pt = "(?<name>\\p{L}+)(?<number>\\d*)";
Matcher m = Pattern.compile(pt).matcher(t.trim());
m.find();
System.out.println("Using [" + pt + "] vs [" + t + "] GC=>" +
m.groupCount());
NameID n = new NameID();
n.name = m.group(1);
if (m.groupCount() > 2) {
try {
String ind = m.group(2);
n.id = Integer.parseInt(ind);
} catch (Exception e) { }
}
最佳答案
String t = "用量2";
String pt = "^(?<name>\\p{L}+)(?<number>\\d*)$";
Matcher m = Pattern.compile(pt).matcher(t.trim());
if (m.matches()) {
String name = m.group("name");
Integer id = m.group("number").length() > 0 ? Integer.parseInt(m.group("number")) : null;
System.out.println("name=" + name + ", id=" + id); // name=用量, id=2
}
您的正则表达式工作正常,但您的 Java 代码有一些问题。请参阅 javadoc 以了解 groupCount()
:
Group zero denotes the entire pattern by convention. It is not included in this count.
关于java - JAVA 的正则表达式获取可选组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44082453/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!