0

I'm trying to get an int from a String. The String will always come as:

"mombojumbomombojumbomombojumbomombojumbomombojumbomombojumbohello=1?fdjaslkd;fdsjaflkdjfdklsa;fjdklsa;djsfklsa;dfjklds;afj=124214fdsamf=352"

The only constant in all of this, is that I will have a "hello=" followed by a number. With just that, I can't figure out how to pull out the number after the "hello=". This is what I have tried so far with no luck.

EDIT: The number will always be followed by a "?"

String[] tokens = s.split("hello=");
for (String t : tokens)
    System.out.println(t);

I can't figure out how to isolate it from both sides of the int.

4

5 回答 5

13
Pattern p = Pattern.compile("hello=(\\d+)");
Matcher m = p.matcher (s);
while (m.find())
    System.out.println(m.group(1));

这将设置搜索s包含 hello= 后跟一位或多位数字(\\d+表示一位或多位数字)的任何地方。循环查找此模式的每次出现,然后每当找到匹配项时,m.group(1)提取数字(因为这些数字在模式中分组)。

于 2013-07-25T21:44:59.500 回答
2

您应该为此使用正则表达式

    String str = "mombojumbomombojumbomombojumbomombojumbomombojumbomombojumbohello=1fdjaslkd;fdsjaflkdjfdklsa;fjdklsa;djsfklsa;dfjklds;afj=124214fdsamf=352";
    Pattern p = Pattern.compile("hello=(\\d+)");
    Matcher m = p.matcher(str);
    if (m.find()) {
        System.out.println(m.group(1)); // prints 1
    }
于 2013-07-25T21:51:18.250 回答
1

尝试这个:

String r = null;
int col = s.indexOf("hello="); // find the starting column of the marker string
if (col >= 0) {
    String s2 = s.substring(col + 6); // get digits and the rest (add length of marker)
    col = 0;
    // now find the end of the digits (assume no plus or comma or dot chars)
    while (col < s2.length() && Character.isDigit(s2.charAt(col))) {
        col++;
    }
    if (col > 0) {
        r = s2.substring(0, col); // get the digits off the front
    }
}

r 将是您想要的字符串,如果没有找到数字,它将为 null。

于 2013-07-25T21:46:41.330 回答
0

另一个非正则表达式解决方案:

String str = "mombojumbomombojumbomombojumbomombojumbomombojumbomombojumbohello=142?fdjaslkd;fdsjaflkdjfdklsa;fjdklsa;djsfklsa;dfjklds;afj=124214fdsamf=352";
char arr[] = str.substring(str.indexOf("hello=")+6).toCharArray();
String buff ="";
int i=0;
while(Character.isDigit(arr[i])){
    buff += arr[i++];
}
int result = Integer.parseInt(buff);
System.out.println(result);
于 2013-07-25T23:38:41.380 回答
0

这是另一种非正则表达式的性能方法。为了您的方便,包装在一个方法中

辅助方法

 public static Integer getIntegerForKey(String key, String s)
 { 
    int startIndex = s.indexOf(key);

    if (startIndex == -1)
        return null;

    startIndex += key.length();

    int endIndex = startIndex;

    int len = s.length(); 

    while(endIndex < len && Character.isDigit(s.charAt(endIndex))) {
        ++endIndex;
    }

    if (endIndex > startIndex)
        return new Integer(s.substring(startIndex, endIndex));

    return null;
 }

用法

Integer result = getIntegerForKey("hello=", yourInputString);

if (result != null)
    System.out.println(result);
else
    System.out.println("Key-integer pair not found.");
于 2013-07-25T22:06:45.133 回答