I want to split a string using methods in Pattern,here is what i did
String s = "[[[0.093493,51.6037],[0.091015,51.5956]]]"
Pattern branchPattern = Pattern.compile("[...]");
String[] split = branchPattern.split(s);
I want to get the result that String[] contains [0.093493,51.6037] and [0.091015,51.5956]. But the result of this code is not the result i want. How can i split this string? Or is there any way like use matcher to split this string in the format i want?
Just do matching instead of splitting.
Pattern p = Pattern.compile("\\[[^\\[\\]]+\\]");
Matcher m = p.matcher(s);
while(m.find())
{
System.out.println(m.group());
}
DEMO
or
string.replaceAll("^\\[{2}|\\]{2}$", "").split(",(?=\\[)");
or
string.replaceAll("^\\[+|\\]+$", "").split("\\],\\[)");
I am trying to answer with another perspective. Have a look.Suppose you have placed parameters in between two special charaters like : #parameter# or parameter or even two differnt signs at a time like *paramter#. We can have list of all these parameters between those signs by this code :
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
public class Splitter {
public static void main(String[] args) {
String pattern1 = "#";
String pattern2 = "#";
String text = "(#n1_1#/#n2_2#)*2/#n1_1#*34/#n4_4#";
Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
Matcher m = p.matcher(text);
while (m.find()) {
ArrayList parameters = new ArrayList<>();
parameters.add(m.group(1));
System.out.println(parameters);
ArrayList result = new ArrayList<>();
result.add(parameters);
// System.out.println(result.size());
}
}
}
Here list result will have parameters n1_1,n2_2,n4_4.
Related
I have a value(String) like "BLD00000001BLD00000002 BLD00000003, BLD00000004".
I want to use Regex """^BLD\d{8}"""
but it didn't work..
I want to return results like (BLD00000001','BLD00000002','BLD00000003 ... )
var regex = Regex("""[\{\}\[\]\/?.,;:|\) *~`!^\-_+<>#\#$%&\\\=\(\'\"]""")
val cvrtBldIds = bldIds.split(regex)
if (cvrtBldIds.joinToString(separator="").length % 11 != 0) {
throw BadRequestException("MSG000343", listOf("빌딩Id", "BLD[숫자8자리]"))
} else {
val res = cvrtBldIds
.filter{it.startsWith("BLD")} // BLD로 시작하는 것만 추출
.joinToString(separator = "','") // 아이디 앞뒤로 ',' 붙이기
bldIds = res
var sb = StringBuffer()
sb.append("'")
sb.append(bldIds)
sb.append("'")
input.bldId = sb.toString()
}
Do it as follows:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "BLD00000001BLD00000002 BLD00000003, BLD00000004";
List<String> list = new ArrayList<String>();
Pattern pattern = Pattern.compile("BLD\\d{8}");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
list.add(matcher.group());
}
System.out.println(list);
}
}
Output:
[BLD00000001, BLD00000002, BLD00000003, BLD00000004]
Notes:
BLD\\d{8} means starting with BLD and then 8 digits.
Java regex tutorial: https://docs.oracle.com/javase/tutorial/essential/regex/
Seems you want to split on a space, or a comma-space combo, or between a digit and the text BLD. The following regex can do that:
,?\s|(?<=\d)(?=BLD)
See regex101 for demo.
Here is how you can extract BLD\d{8} pattern matches in Kotlin using .findall():
val text = """"BLD00000001BLD00000002 BLD00000003, BLD00000004"."""
val matcher = """BLD\d{8}""".toRegex()
println(matcher.findAll(text).map{it.value}.toList() )
// => [BLD00000001, BLD00000002, BLD00000003, BLD00000004]
See the Kotlin demo
I have a String xxxxxxxxsrc="/slm/attachment/63338424306/Note.jpg"xxxxxxxx Now, I want to extract substrings slm/attachment/63338424306/Note.jpg & Note.jpg from the String in to variables i.e. temp1 & temp2.
How can I do that using regex in Java?
Note: 63338424306 could be any random no. & Note.jpg could be anything
like Note.png or abc.jpg or xxxx.yyy etc.
Please help me to extract these two strings using regex.
You can use negative look behind to get file name
((?:.(?<!/))+)\"
and below regex to get full path
/(.*)\"
Sample code
public static void main(String[] args) {
Pattern pattern = Pattern.compile("/(.*)\"");
Pattern pattern1 = Pattern.compile("((?:.(?<!/))+)\"");
String matchString = "/slm/attachment/63338424306/Note.jpg\"xxxxxxxx";
Matcher matcher = pattern.matcher(matchString);
String fullString = "";
while (matcher.find()) {
fullString = matcher.group(1);
}
matcher = pattern1.matcher(matchString);
String fileName = "";
while (matcher.find()) {
fileName = matcher.group(1);
}
System.out.println(fullString + " " + fileName);
}
As per your comment taking the string as declared below in my code:
Please clarify if your input string is not like this or I'm missing something.
public static void main(String[] args) {
String str = "xxxxxxxxsrc=\"/slm/attachment/63338424306/Note.jpg\"xxxxxxxx";
String url = null;
// The below pattern will grab string between quotes
Pattern p = Pattern.compile("\"([^\"]*)\"");
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println(m.group(1));
url = m.group(1);
}
// and this will grab filename from the path(url)
p = Pattern.compile("(?:.(?<!/))+$");
m = p.matcher(url);
while (m.find()) {
System.out.println(m.group());
}
}
I have a method like this :
for(String abc:abcs){
xyz = abc.replaceAll(abc+"\\(", "_"+abc+"\\(");
}
How to avoid replacing few replacements which have specific prefixes for them in java
I tried this :
String data = "Today, abc.xyz is object oriented language";
String regex = "(?<!abc.)xyz";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(data);
System.out.println(matcher.find());
Does this work for you?
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String prefix = "abc";
String replaceWith = " text";
String input = "This xyz is an example xyz to show how you can replace certains values of the xyz.\n"
+ "The xyz can conain any arbitrary xyz, for example abc.xyz.";
Pattern pattern = Pattern.compile("[^" + prefix + "].xyz");
Matcher m = pattern.matcher(input);
while (m.find()) {
input = input.replace(m.group().substring(1), replaceWith);
}
System.out.println(input);
}
}
I have this input:
;Client = tefexx;Test = tgrfdrff;Piemel = thgfress
And this regex:
(;Client = )
The word in the regex would change depending on the needs. But in this case I would want to only return tefexx. I don't understand how to match just that word.
You can try this :
(;Client = (.*?);)
In your exemple, this regexp's second capturing group will hold 'tefexx' only.
This should work /Client = ([a-zA-z]+);/
Here's an example using Pattern and Matcher:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Re {
static String s = ";Client = tefexx;Test = tgrfdrff;Piemel = thgfress";
static String re = ";Client = ([^;]*);";
static public void main(String[] args) {
Pattern pattern = Pattern.compile(re);
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
}
}
$ java Re
tefexx
I've string like below , want to get the value of cn=ADMIN , but dont know how to get to using regex efficient way.
group:192.168.133.205:387/cn=ADMIN,cn=groups,dc=mi,dc=com,dc=usa
well ... like this?
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexSample {
public static void main(String[] args) {
String str = "group:192.168.133.205:387/cn=ADMIN,cn=groups,dc=mi,dc=com,dc=usa";
Pattern pattern = Pattern.compile("^.*/(.*)$");
Matcher matcher = pattern.matcher(str);
if (matcher.matches()) {
String right = matcher.group(1);
String[] parts = right.split(",");
for (String part : parts) {
System.err.println("part: " + part);
}
}
}
}
Output is:
part: cn=ADMIN
part: cn=groups
part: dc=mi
part: dc=com
part: dc=usa
String bubba = "group:192.168.133.205:387/cn=ADMIN,cn=groups,dc=mi,dc=com,dc=usa";
String target = "cn=ADMIN";
for(String current: bubba.split("[/,]")){
if(current.equals(target)){
System.out.println("Got it");
}
}
Pattern for regex
cn=([a-zA-Z0-9]+?),
Your name will be in group 1 of matcher. You can extend character classes if you allow spaces etc.