JAVA RegEx en _ cadena delimitada
Frecuentes
Visto 709 veces
2
OK, I need a RegEx that traps the first word up to underscore character but then capture the next words that may have a underscore character. So, here is a group and the expected result:
gear_Armor_Blessed_Robes = "gear", "Armor" and "Blessed_Robes"
gear_Armor_Chain_Coif = "gear", "Armor" and "Chain_Coif"
gear_Armor_Chain_Hauberk = "gear", "Armor" and "Chain_Hauberk"
gear_Armor_Chain_Shirt = "gear", "Armor" and "Chain_Shirt"
gear_Armor_Chain_Leggings = "gear", "Armor" and "Chain_Leggings"
2 Respuestas
4
There's no need to use a regex for this, just use indexOf
y substring
:
String s = "Armor_Blessed_Robes";
int idx = s.indexOf("_");
System.out.println(s.substring(0, idx)); // Armor
System.out.println(s.substring(idx + 1)); // Blessed_Robes
With regex, you'd have to use the following, which is a tad more complicated and harder to read:
Pattern p = Pattern.compile("([^_]+)_(.+)");
Matcher m = p.matcher(s);
if (m.find()) {
String first = m.group(1); // Armor
String second = m.group(2); // Blessed_Robes
}
Respondido 26 ago 12, 04:08
Sorry, I had to edit the original post, but this is the closest to what I need. - NeoFax
@NeoFax: Do the new strings always start with gear_
? If so, you can easily change the above regex to "gear_([^_]+)_(.+)"
. - Juan Carlos
Yes they do. The script looks for only the JSON value that begins with gear. Perfect! Your code in your comment works great! Thanks! - NeoFax
@NeoFax I don't quite understand why you'd pick this answer when it requires more work. s.split("_", 2)
devolverá una matriz de String
{ "gear", "Armor", "Blessed_Robes" }
- obataku
The reason I chose this one is that I do not have access to s.split. It needs to be RegEx only and Joao's code snippet worked perfectly with the "gear_([^_]+)_(.+)" - NeoFax
4
You can split along _
, limiting the number of splits to 3:
assert Arrays.equals("gear_Armor_Blessed_Robes".split("_", 3),
new String[] { "gear", "Armor", "Blessed_Robes" });
It should give you a String[]
that contains the 3 String
s as specified in your question.
Respondido 26 ago 12, 04:08
@veer: Thanks for modifying my code (since the OP changes the question), but please test your code before modifying the code (not that I'm any better). - nhahtdh
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas java regex or haz tu propia pregunta.
I have to use RegEx due to the fact it is a program that uses JAVA RegEx but I do not have access to the code. - NeoFax