简体   繁体   English

使用正则表达式分割字符串

[英]Split string with regular expression

I have been trying to split a string using regular expression in android without any success. 我一直试图在Android中使用正则表达式拆分字符串,但未成功。

The string is formatted like this id;value| 字符串的格式如下: id | value | For example : 例如 :

String valueString = "20;somevalue|4;anothervalue|10;athirdvalue|5;enoughwithvaluesalready";

I use this method to try o split the string. 我使用此方法尝试o拆分字符串。

public void splitString(String valueString){
    Pattern p = Pattern.compile("([\\d]+);([^\\|]+)");
    Matcher m = p.matcher(valueString);  
    boolean matches = m.matches();
}

When I run it in the Rubular-regex-editor it looks fine, in Android no matches are found. 当我在Rubular-regex-editor中运行它时,它看起来不错,在Android中找不到匹配项。 Any ideas? 有任何想法吗?

the method matches() tries to match the regex against the the complete string. 方法matches()尝试将正则表达式与完整字符串进行匹配。 And this does clearly not match. 这显然不匹配。

find() will find the next matching substring. find()将找到下一个匹配的子字符串。

Why don't you use String.split instead of writing your own solution? 为什么不使用String.split而不是编写自己的解决方案?

Like: 喜欢:

final String[] entries = valueString.split("\\|");
for (String entry : entries) {
  final String[] fields = entry.split(";", 2);
}

I have tried your example, It will work only add .* at end of your Regx 我已经试过您的示例,它只能在Regx末尾添加。*

    Log.i("MainActivity ", "Matches " + valueString.matches("([\\d]+);([^\\|]+).*"));

Above line return true 上面的行返回true

http://developer.android.com/reference/java/lang/String.html#matches(java.lang.String ) http://developer.android.com/reference/java/lang/String.html#matches(java.lang.String

Describe in above function 描述以上功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM