简体   繁体   English

从字符串中删除最后一个“。”字符而不在中间删除

[英]Remove last “.” character/s from a string without removing in middle

I am reading a text file and create a excel file using it. 我正在读取文本文件并使用它创建一个excel文件。 I managed to do the conversion. 我设法做了转换。 But there is a description filed with one or two full-stop(.) that I wanna remove. 但是有一个描述提交了一个或两个我想删除的句号(。)。 Some times there may be have one full-stop, may be have two or may be no full-stop. 有时可能会有一个全站,可能有两个或可能没有全停。 I tried with using replace but it also remove the (.) inside/middle of the text. 我尝试使用替换,但它也删除文本内部/中间的(。)。 I don't wanna do that. 我不想那样做。

These are some samples 这些是一些样本

P/NO 9281195 . .                                 
TFR TO 202 . .                                                               
E/C 21118 GTLA/0267/0044505 NI                                                    
9259589 .PMGN JAYARATHNE .                       
GTLA/0267/0044505 662881724V .  

What I want is 我想要的是

P/NO 9281195                              
TFR TO 202                                                            
E/C 21118 GTLA/0267/0044505 NI                                                    
9259589 .PMGN JAYARATHNE                
GTLA/0267/0044505 662881724V
  1. Solution : 方案:

    You can use a regex that'll match some couple (space point) at the end, and replace this by nothing 您可以使用最后匹配某些(space point)的正则表达式,并将其替换为(space point)

     String line = "P/NO 9281195 . ."; line = line.replaceAll("(\\\\s*\\\\.)+$", ""); 
  2. Details : 细节 :

    • \\s* for 0 to unlimited space \\s*为0到无限空间
    • \\. for a point 一点
    • (\\\\s*\\\\.)+ for 1 to unlimited couples of space/point (\\\\s*\\\\.)+为1到无限的空间/点对
    • $ match at the end $ match最后

Try it 试试吧

str.replaceAll("(\\.|\\s)+$", "")

This regex will match any . 这个正则表达式将匹配任何. character or any space at the end of the line. 字符或行尾的任何空格。 So you just need to replace it with empty string. 所以你只需要用空字符串替换它。

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

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