Serving the Quantitative Finance Community

 
User avatar
Piyushbhatt
Topic Author
Posts: 5
Joined: July 8th, 2022, 5:14 am

How to trim a string after a specific character in java

July 14th, 2022, 1:24 pm

I'm new to the java programming language and I was going through a couple of blogs on wiki and Scaler on the topic trim in java and wanted to understand the logic behind how to trim a string after a specific character in java 

I have a string variable in java having value:
String result="34.1 -118.33\n<!--ABCDEFG-->";
I want my final string to contain the value:

String result="34.1 -118.33";

How can I do this? Your help would be highly appreciated, Thanks in advance!
Hi, I’m Piyush. I’m a Computer Science and Engineering graduate who is passionate about programming and technology. I found this forum in hopes of learning something valuable in programming.
 
User avatar
tags
Posts: 3159
Joined: February 21st, 2010, 12:58 pm

Re: How to trim a string after a specific character in java

July 27th, 2022, 3:55 pm

hey Piy. you may want to use regex.
disclaimers: I haven't written anything in Java in the past 10 years. below works though.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String[] args) {
    Pattern pattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\s*-\\s*\\d{1,3}\\.\\d{1,3}", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher("34.1 -118.33\n<!--ABCDEFG-->");
    boolean matchFound = matcher.find();
    if(matchFound) {
      System.out.println(matcher.group(0));
    } else {
      System.out.println("Match not found");
    }
  }
}