使用正则表达式提取维度测量

时间:2016-08-19 04:03:57

标签: java regex

我正在努力使用正则表达式,它可以从语句中提取类似度量的值。以下是我遇到的一些示例:

示例问题:

  1. 图像像素200x500像素模糊 - 提取200x500像素
  2. 图像像素200 x 500模糊 - 提取200 x 500
  3. 100.22 x 200.55 x 90.55 mm是手机的尺寸 - 提取100.22 x 200.55 x 90.55 mm
  4. 手机尺寸为100.22x200.55x90.55毫米。 - 提取100.22x200.55x90.55 mm
  5. 到目前为止我的代码如下

    
    
    String str_array[] = new String[4];
    		str_array[0] = "Image pixel 200x500 px blur";
    		str_array[1] = "Image pixel 200 x 500 blurring";
    		str_array[2] = "100.22 x 200.55 x 90.55 mm is the size of the handphone";
    		str_array[3] = "The mobile phone is 100.22x200.55x90.55 mm in dimension.";
    		for (int i=0;i<str_array.length;i++){
    			Pattern pty_resolution_ratio_metrics_try = Pattern.compile("(\\d+)[\\.\\d]+(\\s*)x");
    			Matcher matcher_value_metrics_error_try = pty_resolution_ratio_metrics_try.matcher(str_array[i]);
    			while (matcher_value_metrics_error_try.find()) {
    				System.out.println("index: "+i+"-"+matcher_value_metrics_error_try.group(0));
    			}
    		}
    &#13;
    &#13;
    &#13;

    以上代码的结果:

    • 指数:0-200x
    • 指数:1-200 x
    • 指数:2-100.22 x
    • 指数:2-200.55 x
    • 指数:3-100.22x
    • 指数:3-200.55x

    任何正则表达式建议?需要帮助。

    谢谢!

3 个答案:

答案 0 :(得分:0)

public static void getDimensions(String text) {
    Pattern pattern = Pattern.compile("((\\d+.?\\d+)(\\s?)x?\\s?)+");
    Matcher matcher = pattern.matcher(text);
    while (matcher.find()) {
        System.out.println("Index: " + matcher.start()+" Found: " + matcher.group());
    }

}

试试这个

答案 1 :(得分:0)

添加@ngrj添加的内容,为了打印缩写,您可以将其修改为:

<强> Pattern.compile(&#34;((\ d + \ d +)(\'S)P X \ S(毫米))+&#34;??????)

答案 2 :(得分:0)

你可以这个正则表达式:

((?:\\d[\\d\\s\\.x]+\\d)(?:\\s*(?:px|mm))?)

此正则表达式查找2位数字内的所有数字,空格,句点和x。并在数字后面检查pxmm

或者,您可以使用正则表达式进行检查以确保所有内容的顺序正确(数字之间没有空格):

((?:(?:[\\d\\.]+)(?:\\s*x\\s*(?:[\\d\\.]+))+)(?:\\s*(?:px|mm))?)
public static void main(String[] args) {

    String texts[] = {"Image pixel 200x500 px blur",
        "Image pixel 200 x 500 blurring",
        "100.22 x 200.55 x 90.55 mm is the size of the handphone",
        "The mobile phone is 100.22x200.55x90.55 mm in dimension"};

    String regex = "((?:\\d[\\d\\s\\.x]+\\d)(?:\\s*(?:px|mm))?)";

    Pattern p = Pattern.compile(regex);

    for (int q = 0; q < texts.length; q++){
        Matcher m = p.matcher(texts[q]);
        while (m.find()){
            System.out.println(m.group());
        } 
    }
}

打印出以下内容:

200x500 px
200 x 500
100.22 x 200.55 x 90.55 mm
100.22x200.55x90.55 mm