我想检索长度的数量,例如12米,12米,3米,但不能获得3m2或3m3区域的值....我使用正则表达式来获取值。这是我的正则表达式,但它没有运行。 :(
([0-9]+[,.]*[0-9]*\s*(mét|m|cm|dm|mm|km|hm|dam|centimet)+(^[0-9]+))*
答案 0 :(得分:0)
尝试
[0-9]+([,.][0-9]*)?\s*(mét|m|cm|dm|mm|km|hm|dam|centimet)\s*([^\s0-9]|\z)
说明:
答案 1 :(得分:0)
其他方法(每次测试通过):
import static org.junit.Assert.*;
import org.junit.Test;
public class RemoveUnitSpec {
public static String removeUnit(String input) {
for (int i = 0; i < input.length(); i++) {
if(Character.isLetter(input.charAt(i))) {
return input.substring(0, i).trim();
}
}
return input;
}
@Test
public void itShouldDoNothingWhenNoUnit() {
String input = "3,52";
assertEquals("3,52", removeUnit(input));
}
@Test
public void itShouldRemoveUnit() {
String input = "12m";
assertEquals("12", removeUnit(input));
}
@Test
public void itShouldRemoveSquareMeter() {
String input = "12m2";
assertEquals("12", removeUnit(input));
}
@Test
public void itShouldRemoveUnitWithSpace() {
String input = "12 m";
assertEquals("12", removeUnit(input));
}
@Test
public void itShouldRemoveTextualUnitWithSpace() {
String input = "3,2 meters";
assertEquals("3,2", removeUnit(input));
}
}
答案 2 :(得分:0)
我想我会用这样的东西:
([0-9]+(?:[,.][0-9]*)?)\s*(mét|m|cm|dm|mm|km|hm|dam|centimet)([0-9]+)?
然后您可以按如下方式获取字符串的每个部分:
Matcher matcher = RE.matcher(string);
if (matcher.matches) {
String value = matcher.group(1);
String unit = matcher.group(2);
String exp = matcher.group(3); // may be null
...
}