如何在java中进行字符串模式匹配?

时间:2015-05-28 05:25:00

标签: java android string pattern-matching

在我的应用中,我收到了服务器的回复。我得到的时间格式是"PT10H2M1S","PT1H2S","PT0S" etc。如果字符串中存在H,我必须将之前的数字作为小时。如果字符串中存在M,我必须在此之前取数字分钟。如果字符串中存在S,我必须在此之前取数字。我该怎么做?

5 个答案:

答案 0 :(得分:2)

static Pattern p = Pattern.compile("PT(?:([0-9]+)H)?(?:([0-9]+)M)?(?:([0-9]+)S)?");

static void parse(String s){
  Matcher m = p.matcher(s);
  m.find();
  String hh = m.group(1);
  String mm = m.group(2);
  String ss = m.group(3);
  System.out.println("s="+s+" hh="+hh+" mm="+mm+" ss="+ss);
}

答案 1 :(得分:1)

使用PatternMatcher类。

String hours;
String mins;
String secs;
Matcher m = Pattern.compile("(\\d+)H|(\\d+)M|(\\d+)S");
while(m.find())
{
 hours = m.group(1);
 mins = m.group(2);
 secs = m.group(3);
}

答案 2 :(得分:0)

int a,b,c,d,e,f,g,h,i;
permutation per;
per.alloc(9);
per.first();
for (;;)
    {
    if ((per.i[0]+1)
        +(13*(per.i[1]+1)/(per.i[2]+1))+(per.i[3]+1)
        +(12*(per.i[4]+1))
        -(per.i[5]+1)-11
        +((per.i[6]+1)*(per.i[7]+1)/(per.i[8]+1))-10
        ==66)
        {
        a=per.i[0]+'1';
        b=per.i[1]+'1';
        c=per.i[2]+'1';
        d=per.i[3]+'1';
        e=per.i[4]+'1';
        f=per.i[5]+'1';
        g=per.i[6]+'1';
        h=per.i[7]+'1';
        i=per.i[8]+'1';
        // here a,b,c,d,e,f,g,h,i holds the solution
        break;
        }
    if (!per.next()) break;
    }

你需要一个Matcher m = Pattern.compile("(\\d+)H|(\\d+)M|(\\d+)S"); 长度stringstringcontains ("M") ......

答案 3 :(得分:0)

得到小时

>>> simple = pairs[0] 
>>> complex = pairs[2]  
>>> simple
'{key1 value1}'
>>> complex
'{key3 {value with spaces}}'
>>> simple[1:-1]
'key1 value1'
>>> kv = re.split('\s+', simple[1:-1], maxsplit=1)
>>> kv
['key1', 'value1']
>>> kv3 = re.split('\s+', complex[1:-1], maxsplit=1)
>>> kv3
['key3', '{value with spaces}']

得分

>>> kv3 = complex[1:-1].split(' ', maxsplit=1)
>>> kv3
['key3', '{value with spaces}']

获得第二个

public String getHour(String time)
{
    String hourString[] = time.split("H");
    String[] hour = hourString[0].split("T");
    return hour[1];
}

答案 4 :(得分:-1)

使用此

    String s = "PT1H22M18S";
    int hIndex = s.indexOf('H');
    int mIndex = s.indexOf('M');
    int sIndex = s.indexOf('S');

    String hours="",mintues="",seconds="";

    if (hIndex > 0) {
        hours = s.substring(2, hIndex);
    }
    if (mIndex > 0) {
        if (hIndex > 0) {
            mintues= s.substring((hIndex + 1), mIndex);
        } else {
            mintues= s.substring(2, mIndex);
        }
    }
    if (sIndex > 0) {
        if (mIndex > 0) {
            seconds= s.substring((mIndex + 1), sIndex);
        } else {
            if (hIndex > 0) {
                seconds= s.substring((hIndex + 1), sIndex);
            } else {
                seconds= s.substring(2, sIndex);
            }
        }
    }