简体   繁体   English

如何使用正则表达式输入数字?

[英]How to use regex for digit?

I have a string which has digit and words I want to use regex in java. 我有一个包含数字和单词的字符串,我想在Java中使用正则表达式。

String  s="S.No.DistrictMarketPrice 1 Agra Achhnera NIL 2 Agra Agra 1450 3 Agra Fatehabad NIL 4 Agra Fatehpur Sikri 8765 5 Agra Jagner NIL 6 Agra Jarar NIL 7 Agra Khairagarh NIL 8 Agra Shamshabad NIL 9 Aligarh Atrauli 1298 10 Aligarh Chharra NIL";

I want to break this string. 我想打破这个字符串。 I want every string in new line which should start from only exact serino 我希望换行中的每个字符串都应仅从精确的serino开始

How can I get this output 我如何获得此输出

S.No  .District  Market                Price
1      Agra      Achhnera              NIL
2      Agra      Agra                 1450
3      Agra      Fatehabad             NIL
4      Agra      Fatehpur Sikri       8765 

You can replace each number by a new line + the number: 您可以用新行+数字替换每个数字:

String multiline = s.replaceAll("(\\d+)", "\n$1");
  • (\\\\d+) captures the number (\\\\d+)捕获数字
  • $1 refers to the captured number $1代表捕获的数字

Replace any instance of one or more digits with the system line separator followed by the matched digit(s). 用系统行分隔符替换一个或多个数字的任何实例,后跟匹配的数字。

As such: 因此:

String  s = "S.No.DistrictMarketPrice 1 Agra Achhnera NIL 2 Agra Agra NIL 3 Agra Fatehabad NIL 4 Agra Fatehpur Sikri NIL 5 Agra Jagner NIL 6 Agra Jarar NIL 7 Agra Khairagarh NIL 8 Agra Shamshabad NIL 9 Aligarh Atrauli NIL 10 Aligarh Chharra NIL";

System.out.println(
    s.replaceAll("\\d+", System.getProperty("line.separator") + "$0")
);

Output 输出量

S.No.DistrictMarketPrice 
1 Agra Achhnera NIL 
2 Agra Agra NIL 
3 Agra Fatehabad NIL 
4 Agra Fatehpur Sikri NIL 
5 Agra Jagner NIL 
6 Agra Jarar NIL 
7 Agra Khairagarh NIL 
8 Agra Shamshabad NIL 
9 Aligarh Atrauli NIL 
10 Aligarh Chharra NIL

Use this one: 使用这个:

String []splits = s.split("(?<!\\d)(?=\\d+)");

splits contains lines per index: 拆分包含每个索引的行:

S.No.DistrictMarketPrice 
1 Agra Achhnera NIL 
2 Agra Agra NIL 
3 Agra Fatehabad NIL 
4 Agra Fatehpur Sikri NIL 
5 Agra Jagner NIL 
6 Agra Jarar NIL 
7 Agra Khairagarh NIL 
8 Agra Shamshabad NIL 
9 Aligarh Atrauli NIL 
10 Aligarh Chharra NIL

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

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