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
Related
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 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.
I have the following code. I need to check the text for existing any of the words from some list of banned words. But even if this word exists in the text matcher doesn't see it. here is the code:
final ArrayList<String> regexps = config.getProperty(property);
for (String regexp: regexps){
Pattern pt = Pattern.compile("(" + regexp + ")", Pattern.CASE_INSENSITIVE);
Matcher mt = pt.matcher(plainText);
if (mt.find()){
result = result + "message can't be processed because it doesn't satisfy the rule " + property;
reason = false;
System.out.println("reason" + mt.group() + regexp);
}
}
What is wrong? This code can'f find regexp в[ыy][шs]лит[еe], which is regexp in the plainText = "Вышлите пожалуйста новый счет на оплату на Санг, пока согласовывали, уже
прошли его сроки. Лиценз...". I also tried another variants of the regexp but everything is useless
The trouble is elsewhere.
import java.util.regex.*;
public class HelloWorld {
public static void main(String []args) {
Pattern pt = Pattern.compile("(qwer)");
Matcher mt = pt.matcher("asdf qwer zxcv");
System.out.println(mt.find());
}
}
This prints out true. You may want to use word boundary as delimiter, though:
import java.util.regex.*;
public class HelloWorld {
public static void main(String []args) {
Pattern pt = Pattern.compile("\\bqwer\\b");
Matcher mt = pt.matcher("asdf qwer zxcv");
System.out.println(mt.find());
mt = pt.matcher("asdfqwer zxcv");
System.out.println(mt.find());
}
}
The parenthesis are useless unless you need to capture the keyword in a group. But you already have it to begin with.
Use ArrayList's built in functions indexOf(Object o) and contains(Object o) to check if a String exists anywhere in the Array and where.
e.g.
ArrayList<String> keywords = new ArrayList<String>();
keywords.add("hello");
System.out.println(keywords.contains("hello"));
System.out.println(keywords.indexOf("hello"));
outputs:
true
0
Try this to filter out messages which contain banned words using the following regex which uses OR operator.
private static void findBannedWords() {
final ArrayList<String> keywords = new ArrayList<String>();
keywords.add("f$%k");
keywords.add("s!#t");
keywords.add("a$s");
String input = "what the f$%k";
String bannedRegex = "";
for (String keyword: keywords){
bannedRegex = bannedRegex + ".*" + keyword + ".*" + "|";
}
Pattern pt = Pattern.compile(bannedRegex.substring(0, bannedRegex.length()-1));
Matcher mt = pt.matcher(input);
if (mt.matches()) {
System.out.println("message can't be processed because it doesn't satisfy the rule ");
}
}