Java- Extract part of a string between two special characters

ε祈祈猫儿з 提交于 2019-11-27 13:12:01

Try this regular expression:

'(.*?)"

As a Java string literal you will have to write it as follows:

"'(.*?)\""

Here is a more complete example demonstrating how to use this regular expression with a Matcher:

Pattern pattern = Pattern.compile("'(.*?)\"");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
    System.out.println(matcher.group(1));
}

See it working online: ideone

If you'll always have a string like that (with 3 parts) then this is enough:

 String str= "21*90'89\"";
 String between = str.split("\"|'")[1];

Another option, if you can assure that your strings will always be in the format you provide, you can use a quick-and-dirty substring/indexOf solution:

str.substring(str.indexOf("'") + 1, str.indexOf("\""));

And to get the second piece of data you asked for:

str.substring(0, str.indexOf("*"));
public static void main(final String[] args) {
    final String str = "21*90'89\"";
    final Pattern pattern = Pattern.compile("[\\*'\"]");
    final String[] result = pattern.split(str);
    System.out.println(Arrays.toString(result));
}

Is what you are looking for... The program described above produces:

[21, 90, 89]

I'm missing the simplest possible solution here:

str.replaceFirst(".*'(.*)\".*", "$1");

This solution is by far the shortest, however it has some drawbacks:

  • In case the string looks different, you get the whole string back without warning.
  • It's not very efficient, as the used regex gets compiled for each use.

I wouldn't use it except as a quick hack or if I could be really sure about the input format.

    String str="abc#defg@lmn!tp?pqr*tsd";               
    String special="!?@#$%^&*()/<>{}[]:;'`~";           
    ArrayList<Integer> al=new ArrayList<Integer>();         
    for(int i=0;i<str.length();i++)
    {
        for(int j=0;j<special.length();j++)
            if(str.charAt(i)==special.charAt(j))        
                al.add(i);
    }
    for(int i=0;i<al.size()-1;i++)
    {
        int start=al.get(i);
        int end=al.get(i+1);
        for(int j=start+1;j<end;j++)
            System.out.print(str.charAt(j));
        System.out.print(" ");
    }
Dead Programmer
String str= 21*90'89;
String part= str.split("[*|']");
System.out.println(part[0] +""+part[1]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!