使用通配符拆分字符串 [英] Splitting String with wildcard

查看:38
本文介绍了使用通配符拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量字符串,其中包含我需要的值和拆分器.问题是,字符串的长度是可变的,拆分器的类型也是如此.它们通过 XML 文件到达.

I have a variable String which contains values i need and splitters. The problem is, the length of the string is variable and the type of splitters as well. They arrive through XML-file.

一个字符串看起来像这样:

A string will look like this:

1+"."+20+"."+51+"."+2+"name.jpg"

但也可以是:

1+"*"+20+"*"+51+"name.jpg"

坚实的因素是:数字是我需要检索的 ID.分隔符值将在引号"之间.

The solid factors are: the digits are id's which I need to retrieve. the splitter values will be between "quotes".

id 的数量未知,可以是 1,可以是 200用于拆分的值可以是所有内容,但总是在两个引号之间.

the amount of id's is unknown, can be one, can be 200 the value used to split can be everything, but will always be between two quotes.

我正在寻找一种在."上拆分字符串的方法,但不是点(.),而是给出一个通配符,它​​可以是 1 个字符或多个.

I was looking for a way to split the string on the "." but instead of the dot (.) give a wildcard, which can be 1 character or multiple.

注意:引号之间的值可以是任何值!甚至不必是单个字符

推荐答案

尝试按正则表达式拆分,即像这样:

Try to split by regular expression, i.e. like this:

String regex = "\\+?\"[^\"]*\"\\+?";
System.out.println(Arrays.toString( "1+\".\"+20+\".\"+51+\".\"+2+\"name.jpg\"".split( regex ) ));
System.out.println(Arrays.toString( "1+\"*\"+20+\"*\"+51+\"name.jpg\"".split( regex ) ));

输出:

[1, 20, 51, 2]
[1, 20, 51]

正则表达式将匹配任何 2 个双引号,中间有非双引号字符,前面/后面是可选的加号.您也可以扩展它以允许空格,例如"\\s*\\+?\\s*\"[^\"]*\"\\s*\\+?\\s*".唯一不允许的在拆分器中将是双引号.

The regex would match any 2 double quotes with non-double quote characters in between and preceeded/followed by optional pluses. You could expand that to allow whitespace as well, e.g. "\\s*\\+?\\s*\"[^\"]*\"\\s*\\+?\\s*". The only thing that's not allowed in a splitter would be double quotes.

如果您还需要名称,您可以尝试在正则表达式中定义潜在的拆分器,
例如"(\\+?\"[\\.\\*]*\"\\+?)|\\+?\""

If you need the name as well, you might try and define the potential splitters in the regex,
e.g. "(\\+?\"[\\.\\*]*\"\\+?)|\\+?\""

请注意,在这种情况下,您必须考虑名称周围的引号,即拆分 2+"name.jpg" 您必须添加替代 \+?"(双引号前面是一个可选的加号).

Note that in that case you'd have to account for the quotes around the name, i.e. to split 2+"name.jpg" you have to add the alternative \+?" (double quotes preceded by an optional plus).

更新:

其他示例(输入 -> 输出)

Additional examples (input -> output)

5+".."+272+"..."+21+"splitter"+2+"name.jpg" --> [5, 272, 21, 2]
444+"()"+0+"abc"+51+"__"+2+"name.jpg" --> [444, 0, 51, 2]
1+"."+20+"."+51+"."+2+"name.jpg" --> [1, 20, 51, 2]
1+"*"+20+"*"+51+"name.jpg" --> [1, 20, 51]

这篇关于使用通配符拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆