dポイントプレゼントキャンペーン実施中!

javaで以下のような文字列がある場合、特定文字列から特定文字列までを取得したいのですが、
良い方法ありませんでしょうか?

例)c=の数値部分を取得する。
String str = "a=111 b=3333 c=446363634 d=35252 e=76738989";
int strIndex = str.indexOf("c=");
String str2 = str.substring(strIndex+3,XXXX);

XXX部分をどう書いたらよいかわからず。
そもそもsubstringでは取得できない感じなのでしょうか?
実際はリストの各文字列の"C="の値取得したいため、桁数指定できません(c=の桁数は固定でないため)
c=から最初の半角スペースまでとかで取得することが可能でしょうか。

A 回答 (4件)

質問の趣旨とは異なるけど、私なら split か正規表現の


マッチでやるかな。

c= の後に d= が有るとか仮定できるなら、
いろいろできそうだけど、それでも不細工そう(^^;

カンマや空白区切りでsplitして、 = でsplit して trim が
無難そう。
    • good
    • 0

String str = "a=111 b=3333 c=446363634 d=35252 e=76738989";


int strIndex = str.indexOf("c=");//==13
int strIndex2 = str.indexOf(" ",strIndex );//==24
if(strIndex !=-1 && strIndex2 !=-1)   //cの後もデータがある場合
 str.substring(strIndex+2,strIndex2); //15,24
else if(strIndex !=-1)   //c以降にデータがない場合(~634で終わり)
 str.substring(strIndex+2); //15以降全部
    • good
    • 0

正規表現なら、


https://www.javadrive.jp/start/regex/index13.html

import java.util.*;
import java.util.regex.*;

public class Main {
public static void main(String[] args) throws Exception {
// Your code here!

String str = "a=111 b=3333 c=446363634 d=35252 e=76738989";
String regex ="(c=\\d+)\s";

Pattern p = Pattern.compile(regex);

Matcher m = p.matcher(str);
if (m.find()){
System.out.println(m.group(1));
}
}
}

初心者レベルですが・・・
    • good
    • 0

class Main {


 public static void main(String[] arg) {
  String str = "a=111 b=3333 c=446363634 d=35252 e=76738989";
  int strIndex = str.indexOf("c=");
  String str2 = str.substring(strIndex+2).split(" ")[0];
  System.out.println(str2);
 }
}
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!