0

I have a string whose first character is "^". I want to extract the string without this character. For eg : "^coal" should become "coal". Following is the code I wrote, but I don't know why it's not working.

public void RegEx(String s1){
        System.out.println(s1.substring(0,1));  //to check if i am ok.
        if((s1.substring(0,1)).equals("^")){
            Pattern p = Pattern.compile("^");
            String[] extracted = p.split(s1);
            for(String s: extracted){
                System.out.println(s);
            }
        }
    }

s1 = "^coal". Output = "^coal".

2
  • 4
    I'm not a javascript expert, but if you're trying to remove the first character, can't you just do s1 = s1.substring(1); inside your if statement? For example, "MyString".substring(1); evaluates to "yString" Commented Aug 14, 2016 at 6:15
  • This is just a fragment of a larger problem. So I really need to know the official way. Thanks though. Commented Aug 14, 2016 at 6:18

3 Answers 3

5

The ^ character has special meaning in a regex so you need to escape it: "\\^".

But a regex is not the most efficient way to do this. Just use substring:

if (s1.startsWith("^")) {
    s1 = s1.substring(1);
}
System.out.println(s1);

Note: as you see above you can also use startsWith to easily check if a string starts with some other string.

Sign up to request clarification or add additional context in comments.

1 Comment

Knew I shoulda posted my comment as an answer :) +1!
1

The character ^ is significant in a regular expression. Escape it like,

Pattern p = Pattern.compile("\\^");

Comments

0

Use this using indexOf method. It is short and more efficient

 String s="^coal";
 int l=s.indexOf("^");
 System.out.println(s.substring(l+1));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.