如何在字符串中的问号(?)后删除尾随字符?

时间:2015-10-09 11:28:53

标签: java regex string replaceall

我需要从下面的String

中删除2之后的尾随字符
String a = "12?34567";

我期望的字符串输出应为12

我尝试了以下replaceAll方法。但它没有用。

a.replaceAll("\\?+$", ""));

请帮忙

3 个答案:

答案 0 :(得分:3)

使用indexOf:

而不是使用正则表达式
final int index = orig.indexOf('?');
return index == -1 ? orig : orig.subString(0, index);

如果您想保留问号,只需在上面的子字符串操作中将{1}添加到index

答案 1 :(得分:0)

您忘记在正则表达式中添加数字,您只是检查一个或多个问号实例。这应该是你想要实现的目标。

String a = "12?34567";
System.out.println(a.replaceAll("\\?\\d*$", ""));

如果您只想在评论中所述的第一个问号后删除它们,您可以直接执行

String a = "12??1?1231";
System.out.println(a.replaceAll("\\?.*", ""));

答案 2 :(得分:0)

$id = $_POST["user_id"];
$facebook = $_POST["facebookId"];
$userInfos = $_POST["userInfos"];

$json = json_decode($userInfos, true);

        $coins = $json['coins'];
        $score =  $json['score'];
        $highest_coins = $json['highest_coins'];
        $upgrades = $json['upgrades'];
> line 89
        $sql = "UPDATE app_user SET coins = ?, score = ?, highest_coins = ? WHERE user_id = ?";
        $stmt->bind_param('iiis',$coins,$score,$highest_coins,$id);
        $nb = $stmt->execute();
line 99
            foreach(is_array($upgrades) as $person => $value)
            {
                $character_id =  $value['character_id'];
                $upgrade_id =  $value['upgrade_id'];
                $upgrade_level =  $value['upgrade_level'];

                $sql = "UPDATE user_upgrades SET upgrade_level = ? WHERE facebook_id = ? AND character_id = ? AND upgrade_id = ?";
                $stmt->bind_param('isii', $upgrade_level, $facebook, $character_id, $upgrade_id);
                $nb = $stmt->execute();
            }