2

I have some strings Like

1.IND_FROM_ONE_TO_FIVE  
2.IND_FROM_FIVE_TO_TEN  
3.BS_FROM_ONE_TO_FIVE 
4.BS_FROM_FIVE_TO_TEN   
5.OP_FROM_ONE_TO_FIVE  
6.OP_FROM_FIVE_TO_TEN

And I want to cut from all of them everything before the first "" include ""!!!.

Something like :

1.IND_FROM_ONE_TO_FIVE => FROM_ONE_TO_FIVE

2.IND_FROM_FIVE_TO_TEN => FROM_FIVE_TO_TEN

3.BS_FROM_ONE_TO_FIVE => FROM_ONE_TO_FIVE

4.BS_FROM_FIVE_TO_TEN => FROM_FIVE_TO_TEN etc.

I have tried /[^_]*/ but it returns IND_FROM_ONE_TO_FIVE => _FROM_ONE_TO_FIVE (did not cut first "_")

How could I make it on java?

3 Answers 3

2

You can prepend an anchor and match the underscore after is as well. In the replacement use an empty string.

^[^_]*_

Regex demo | Java demo

Using replaceFirst you can omit the anchor:

System.out.println("IND_FROM_ONE_TO_FIVE".replaceFirst("[^_]*_", ""));

Output

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

Comments

1

You could use a capturing group to extract substring that you want to.

^[^_]+_(.*)

I also tried to test result on Java.

import java.util.regex.*;
public class MyClass {
    public static void main(String args[]) {
        String mydata = "BS_FROM_FIVE_TO_TEN";
        Pattern pattern = Pattern.compile("^[^_]+_(.*)");
        Matcher matcher = pattern.matcher(mydata);
        if (matcher.find())
        {
            System.out.println(matcher.group(1));
        }
    }
}

Result

FROM_FIVE_TO_TEN

Comments

0

You can use matching rather than replacing: take the first and only capture from this regex (multiline): ^\d+\.[^_]+_(.*)$ (https://regex101.com/r/Y3Ztv4/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.