Java 如何删除£;是否从数组对象中提取符号并保存?

Java 如何删除£;是否从数组对象中提取符号并保存?,java,regex,Java,Regex,我正在为一个大学项目编写一个基本聊天机器人。用户必须通过输入金额来设置预算。目前,该程序能够在用户消息中搜索数字并正确保存。但是,如果在其前面加上英镑符号,则由于消息中有英镑符号,因此无法将其另存为整数 这是我的代码: //Scan the user message for a budget amount and save it. for (int budgetcount = 0; budgetcount < words.length; budgetcount++) {

我正在为一个大学项目编写一个基本聊天机器人。用户必须通过输入金额来设置预算。目前,该程序能够在用户消息中搜索数字并正确保存。但是,如果在其前面加上英镑符号,则由于消息中有英镑符号,因此无法将其另存为整数

这是我的代码:

//Scan the user message for a budget amount and save it.
    for (int budgetcount = 0; budgetcount < words.length; budgetcount++) 
    {
        if (words[budgetcount].matches(".*\\d+.*"))
        {
            if (words[budgetcount].matches("\\u00A3."))
            {
                words[budgetcount].replace("\u00A3", "");
                System.out.println("Tried to replace a pound sign");
                ResponsesDAO.budget = Integer.parseInt(words[budgetcount]);
            }
            else
            {
                System.out.println("Can't find a pound sign here.");
            }
        }
//扫描用户消息以获取预算金额并保存它。
对于(int-budgetcount=0;budgetcount
我以前尝试过使用.contains()和其他方法来表示我要删除的是英镑符号,但仍然得到“此处找不到英镑符号”。打印出来

如果有人能提供建议或纠正我的代码,我将不胜感激


提前感谢!

JAVA中的字符串是不可变的。您正在替换,但从未将结果分配回
单词[budgetcount]

更改代码中的以下行

words[budgetcount] = words[budgetcount].replace("\u00A3", "");
另一种方法是使用
Character.isDigit(…)
识别一个数字,然后编织一个仅限数字的字符串,该字符串稍后可以解析为整数

代码片段:

private String removePoundSign(final String input) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < input.length(); i++) {
        char ch = input.charAt(i);
        if (Character.isDigit(ch)) {
            builder.append(ch);
        }
    }
    return builder.toString();
}
System.out.println(removePoundSign("£12345"));
12345
输出:

private String removePoundSign(final String input) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < input.length(); i++) {
        char ch = input.charAt(i);
        if (Character.isDigit(ch)) {
            builder.append(ch);
        }
    }
    return builder.toString();
}
System.out.println(removePoundSign("£12345"));
12345

您还可以使用
String.replaceAll
方法

代码段:

public class TestClass {

    public static void main(String[] args){

        //Code to remove non-digit number
        String budgetCount = "£34556734";
        String number=budgetCount.replaceAll("[\\D]", "");
        System.out.println(number);

        //Code to remove any specific characters
        String special = "$4351&2.";
        String result = special.replaceAll("[$+.^&]",""); // regex pattern
        System.out.println(result);

    }
}
输出:

34556734
43512

if(单词[budgetcount]。匹配(“\\u00A3”))
应该只使用1个反斜杠。这将只匹配2个字符的字符串,第一个将是您的英镑符号……这是个好问题……在英国脱欧时期:D-因此投票了!很抱歉这个O/T,但即使在stackoverflow上,也必须有时间简短地笑一笑;)非常感谢!已经排序好了。:)