构建这个正则表达式的问题[1,2,3] [英] Problems with building this regex [1,2,3]

查看:155
本文介绍了构建这个正则表达式的问题[1,2,3]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题需要构建以下正则表达式:
[1,2,3,4]

i have a problem to build following regex: [1,2,3,4]

我找到了解决办法,但我认为它的丑陋

i found a work-around, but i think its ugly

String stringIds = "[1,2,3,4]";
stringIds = stringIds.replaceAll("\\[", ""); 
stringIds = stringIds.replaceAll("\\]", "");
String[] ids = stringIds.split("\\,");

有人可以帮我构建一个正则表达式,我可以在分割函数中使用
感谢您的帮助

Can someone help me please to build one regex, which i can use in the split function Thanks for help

编辑:
i希望从这个字符串[1,2,3,4]获得一个包含4个条目的数组。条目是字符串中的4个数字,所以我需要消除[,]和,。 ,不是问题。
第一个和最后一个数字包含[或]。所以我需要使用replaceAll修复。但我想如果我使用分裂正则表达式,,我也可以通过一个正则表达式,消除[]。但我无法弄清楚,这个正则表达式应该是什么样的。

edit: i want to get from this string "[1,2,3,4]" to an array with 4 entries. the entries are the 4 numbers in the string, so i need to eliminate "[","]" and ",". the "," isn't the problem. the first and last number contains [ or ]. so i needed the fix with replaceAll. But i think if i use in split a regex for ",", i also can pass a regex which eliminates "[" "]" too. But i cant figure out, who this regex should look like.

推荐答案

这几乎就是你要找的东西:

This is almost what you're looking for:

    String q = "[1,2,3,4]";
    String[] x = q.split("\\[|\\]|,");

问题是由于领先的开放式括号,它在数组的开头产生了一个额外的元素。你可能无法用一个正则表达式sansanigans做你想要的。如果您知道字符串始终以开括号开头,则可以先将其删除。

The problem is that it produces an extra element at the beginning of the array due to the leading open bracket. You may not be able to do what you want with a single regex sans shenanigans. If you know the string always begins with an open bracket, you can remove it first.

正则表达式本身意味着(拆分)任何开括号,或任何封闭的括号,或任何逗号。

The regex itself means "(split on) any open bracket, OR any closed bracket, OR any comma."

标点字符在正则表达式中经常具有其他含义。双引导反斜杠......呃,第一个反斜杠告诉Java String解析器下一个反斜杠不是特殊字符(例如:\ n是换行符......)所以 \\ 的意思是我想要一个诚实的上帝反斜杠。下一个反斜杠告诉regexp引擎 next 字符(例如 [不是一个特殊的正则表达式字符。这让我大声笑。

Punctuation characters frequently have additional meanings in regular expressions. The double leading backslashes... ugh, the first backslash tells the Java String parser that the next backslash is not a special character (example: \n is a newline...) so \\ means "I want an honest to God backslash". The next backslash tells the regexp engine that the next character ([ for example) is not a special regexp character. That makes me lol.

这篇关于构建这个正则表达式的问题[1,2,3]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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