Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/402.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
解析字符串javaget索引_Java_String - Fatal编程技术网

解析字符串javaget索引

解析字符串javaget索引,java,string,Java,String,我有很多这种类型的变量字符串 String 1 = s3345 section sector ground String 2= s35 section sector ground String 3= s99983 section sector ground 我只需要取s的值,但这个值不是固定的,而是可变的。 如何找到s的最终索引?假设您希望获得s3345等的数值,并且该部分可以位于字符串中的任何位置,请尝试使用正则表达式替换该值: String input = "s3345 s

我有很多这种类型的变量字符串

  String 1 = s3345 section sector ground
  String 2=  s35 section sector ground
  String 3=  s99983 section sector ground
我只需要取s的值,但这个值不是固定的,而是可变的。
如何找到s的最终索引?

假设您希望获得
s3345
等的数值,并且该部分可以位于字符串中的任何位置,请尝试使用正则表达式替换该值:

String input = "s3345 section sector ground";
String number = input.replace(".*\\bs(\\d+)\\b.*", "$1"); //number would be "3345"

如果您的输入字符串有点固定,即它总是
s section section sector
,您可以将其添加到正则表达式中以使其更严格。

假设数字总是在开始时出现

 String s = "s3345 section sector ground";
 System.out.println((s.split(" "))[0]); //check has to be applied for empty string.

我假设您只需要每个变量中的数字作为字符串

    String one   = "s3345 section sector ground";
    String two   = "s35 section sector ground";
    String three = "s99983 section sector ground";

    // better off importing Scanner normally like this:
    // import java.util.*;
    // the star means to import every class including Scanner
    java.util.Scanner in = new java.util.Scanner(one);
    String num = in.next();
    num = num.substring(1,num.length());

    System.out.println(num);
新手提示:

  • 小心命名变量。它们应该以字母或下划线开头。不是数字
  • 确保每个字符串文字(值)都在双引号内
  • 确保用分号-->结束每条语句
这甚至可以编译吗?哪个是?第一个或任何s?您可以使用
拆分字符串,如果您的数字位于起始位置,则使用拆分文本的第一部分。该正则表达式将适合s前面的任何字符,如as3345,因此我将使正则表达式与前面和后面的空格匹配,如“*\\ss(\\d+\\s.*”@sharonbn如果字符串前面有空格,那么是的。一个更好的解决方案是单词boundary
\b
——我会加上它。