0

次の形式の文字列があります。

<+923451234567>: こんにちは、本文です。

ここで、携帯電話番号(英数字以外の文字なし)、つまり < > 記号の間の文字列の先頭にある 923451234567 と、テキスト、つまり Hi ここにテキストを取得したいと考えています。

これで、現在行っているハードコードされたロジックを配置できます。

String stringReceivedInSms="<+923451234567>: Hi here is the text.";

String[] splitted = cpaMessage.getText().split(">: ", 2);
String mobileNumber=MyUtils.removeNonDigitCharacters(splitted[0]);
String text=splitted[1];

正規表現で文字列から必要な文字列をきれいに取得するにはどうすればよいですか? 文字列の形式が変わるたびにコードを変更する必要がないように。

4

4 に答える 4

3
String stringReceivedInSms="<+923451234567>: Hi here is the text.";

Pattern pattern = Pattern.compile("<\\+?([0-9]+)>: (.*)");
Matcher matcher = pattern.matcher(stringReceivedInSms);
if(matcher.matches()) {
    String phoneNumber = matcher.group(1);
    String messageText = matcher.group(2);
}
于 2013-04-11T10:19:12.653 に答える
2

正規表現を使用する必要があります。次のパターンが機能します。

^<\\+?(\\d++)>:\\s*+(.++)$

使用方法は次のとおりです-

public static void main(String[] args) throws IOException {
    final String s = "<+923451234567>: Hi here is the text.";
    final Pattern pattern = Pattern.compile(""
            + "#start of line anchor\n"
            + "^\n"
            + "#literal <\n"
            + "<\n"
            + "#an optional +\n"
            + "\\+?\n"
            + "#match and grab at least one digit\n"
            + "(\\d++)\n"
            + "#literal >:\n"
            + ">:\n"
            + "#any amount of whitespace\n"
            + "\\s*+\n"
            + "#match and grap the rest of the string\n"
            + "(.++)\n"
            + "#end anchor\n"
            + "$", Pattern.COMMENTS);
    final Matcher matcher = pattern.matcher(s);
    if (matcher.matches()) {
        System.out.println(matcher.group(1));
        System.out.println(matcher.group(2));
    }
}

フラグを追加したPattern.COMMENTSので、将来の参照用に埋め込まれたコメントでコードが機能します。

出力:

923451234567
Hi here is the text.
于 2013-04-11T10:28:02.730 に答える
2

パターンに一致する正規表現を使用します -<\\+?(\\d+)>: (.*)

PatternおよびMatcherJava クラスを使用して、入力文字列を照合します。

Pattern p = Pattern.compile("<\\+?(\\d+)>: (.*)");
Matcher m = p.matcher("<+923451234567>: Hi here is the text.");
if(m.matches())
{
    System.out.println(m.group(1));
    System.out.println(m.group(2));
}
于 2013-04-11T10:17:39.657 に答える
0

次のようにするだけで電話番号を取得できます。

stringReceivedInSms.substring(stringReceivedInSms.indexOf("<+") + 2, stringReceivedInSms.indexOf(">"))

このスニペットを試してください:

public static void main(String[] args){
        String stringReceivedInSms="<+923451234567>: Hi here is the text.";

        System.out.println(stringReceivedInSms.substring(stringReceivedInSms.indexOf("<+") + 2, stringReceivedInSms.indexOf(">")));
    }

文字列を分割する必要はありません。

于 2013-04-11T10:18:09.957 に答える