[英]Java- Extract part of a string between two special characters
I have been trying to figure out how to extract a portion of a string between two special characters ' and " I've been looking into regex, but frankly I cannot understand it. 我一直试图找出如何在两个特殊字符之间提取字符串的一部分'和'我一直在研究正则表达式,但坦率地说我无法理解它。
Example in Java code: Java代码中的示例:
String str="21*90'89\"";
I would like to pull out 89 我想退出89
In general I would just like to know how to extract part of a string between two specific characters please. 一般来说,我只想知道如何在两个特定字符之间提取字符串的一部分。
Also it would be nice to know how to extract part of the string from the beginning to a specific character like to get 21. 如果知道如何从一开始就将部分字符串提取到特定字符(例如获得21),那将会很高兴。
Try this regular expression: 试试这个正则表达式:
'(.*?)"
As a Java string literal you will have to write it as follows: 作为Java字符串文字,您必须按如下方式编写它:
"'(.*?)\""
Here is a more complete example demonstrating how to use this regular expression with a Matcher
: 这是一个更完整的示例,演示如何将此正则表达式与
Matcher
一起使用:
Pattern pattern = Pattern.compile("'(.*?)\"");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
If you'll always have a string like that (with 3 parts) then this is enough: 如果你总是有这样的字符串(有3个部分)那么这就足够了:
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: 另一种选择,如果您可以确保您的字符串始终采用您提供的格式,则可以使用快速且脏的子字符串/ indexOf解决方案:
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]
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(" ");
}
I'm missing the simplest possible solution here: 我在这里错过了最简单的解决方案:
str.replaceFirst(".*'(.*)\".*", "$1");
This solution is by far the shortest, however it has some drawbacks: 这个解决方案是迄今为止最短的解决方案,但它有一些缺点:
I wouldn't use it except as a quick hack or if I could be really sure about the input format. 我不会使用它,除非作为一个快速黑客或我真的可以确定输入格式。
String str= 21*90'89;
String part= str.split("[*|']");
System.out.println(part[0] +""+part[1]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.