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.
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 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 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.
I am trying to generate a dynamic message that can be used for processing using Java and Regular Expressions. My incoming value can be just "$bdate$" or be embedded within a sentence like "Your Birthdate : $bdate$". I want to replace these $aaa$ values dynamically at run time and am not able to isolate the regex matched values within a sentence. Here is what I have so far....
package com.test;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
public class TestRegex {
public static String REGEX = "\\$((?:[a-zA-Z0-9_ ]*))\\$";
public static String testString = "Summary : $summary$"
+ "Age : $age$"
+ "Location : $location$";
public static void main(String[] args) {
System.out.println("Matcher : " + Pattern.matches(REGEX, "$ABX_ 11$"));
String [] splitStrings = testString.split("\\W+"); //also tried "\\b+"
List<String> stringList = Arrays.asList(splitStrings);
for(String test : stringList) {
System.out.println("Split Word : " + test);
}
}
}
The output is below - it misses the preceding and succeeding $ symbols:
Matcher : true
Split Word : Summary
Split Word : summary
Split Word : Age
Split Word : age
Split Word : Location
Split Word : location
I know I am very close but not able to figure out the issue - Can anyone please help !!
You can use the following:
String pattern = "\\w+|\\$\\w+\\$";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(testString);
while (m.find( )) {
System.out.println("Found value: " + m.group(0) );
}
See Ideone DEMO
Just to extend #Karthik's answer and complete the thread, below code snippet only looks for words that match a pattern within the sentence and collects them - it might be easier to replace those dynamically at run time.
package com.test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestRegex {
public static String testString = "Summary : $summary$"
+ "Age : $age$"
+ "Location : $location$";
public static void main(String[] args) {
String pattern = "\\$\\w+\\$";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(testString);
while (m.find( )) {
System.out.println("Found value: " + m.group(0) );
}
}
}
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