简体   繁体   English

使用扫描仪分隔字符串

[英]Using Scanner for separating a string

I'm trying to separate the numbers (including Double) from a string such as "4+5*(4.5+6)". 我正在尝试从诸如“ 4 + 5 *(4.5 + 6)”的字符串中分离数字(包括Double)。 I thought about using a scanner to separate the numbers from my string. 我考虑过使用扫描仪将数字与字符串分开。 I would like to hear if there is a better way to do it, and to know how can i do it with a Scanner? 我想听听是否有更好的方法来做,并想知道如何使用扫描仪来做? This is my code, just wanted to check if it works and it threw an Exception... 这是我的代码,只想检查它是否有效并引发异常...

package testzehavit;

import java.util.Scanner;

public class main {

    public static void main(String[] args) {
        Scanner s= new Scanner("443+54+24");
        s.useDelimiter("+");
        System.out.println(s.next());

    }

}

Thank you 谢谢

The scanner delimiters are regex. 扫描仪定界符是正则表达式。 The symbol '+' is used in regexes for saying "one or more times". 正则表达式中使用符号“ +”表示“一次或多次”。

What you want to do is: 您想要做的是:

public static void main(String[] args) {
    Scanner s= new Scanner("443+54+24");
    s.useDelimiter("\\+");
    System.out.println(s.next());

}

Coming from this question/answer you have to escape the + since the method takes regular expressions and not literal strings. 来自这个问题/答案,您必须转义+因为该方法采用正则表达式而不是文字字符串。 In Java you escape with double backslash \\\\ . 在Java中,您使用双反斜杠\\\\进行转义。 This code: 这段代码:

public static void main(String[] args) {
    Scanner s = new Scanner("443+54+24");
    s.useDelimiter("\\+");
    System.out.println(s.next());
}

prints 443 版画443

Use String.contains(); 使用String.contains(); method. 方法。 You could put a regular expression that represents the range of numbers and operands inside that, or do a simple for-loop and parse each iteration to String to pass it as an argurment to contains method. 您可以在其中放置一个表示数字和操作数范围的正则表达式,或者执行简单的for循环并将每个迭代解析为String,以将其作为参数传递给contains方法。

Sorry for not demonstrating any code but I'm on my phone. 抱歉,没有显示任何代码,但我在手机上。 Google String.contains() and Regular Expression. Google String.contains()和正则表达式。 You should be able to combine the two. 您应该能够将两者结合起来。

public static void main(String[] args) { 公共静态void main(String [] args){

Scanner s = new Scanner("443+54+24");

s.useDelimiter("\\+");

System.out.println(s.next());

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM