Words inside square brackes - RegExp - java

String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String text = "[build]/directory/[something]/[build]/";
RegExp reg = RegExp.compile(linkPattern,"g");
MatchResult matchResult = reg.exec(text);
for (int i = 0; i < matchResult.getGroupCount(); i++) {
System.out.println("group" + i + "=" + matchResult.getGroup(i));
}
I am trying to get all blocks which are encapsulated by squared bracets form a path string:
and I only get group0="[build]" what i want is:
1:"[build]" 2:"[something]" 3:"[build]"
EDIT:
just to be clear words inside the brackets are generated with random text
public static String genText()
{
final int LENGTH = (int)(Math.random()*12)+4;
StringBuffer sb = new StringBuffer();
for (int x = 0; x < LENGTH; x++)
{
sb.append((char)((int)(Math.random() * 26) + 97));
}
String str = sb.toString();
str = str.substring(0,1).toUpperCase() + str.substring(1);
return str;
}
EDIT 2:
JDK works fine, GWT RegExp gives this problem
SOLVED:
Answer from Didier L
String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String result = "";
String text = "[build]/directory/[something]/[build]/";
RegExp reg = RegExp.compile(linkPattern,"g");
MatchResult matchResult = null;
while((matchResult=reg.exec(text)) != null){
if(matchResult.getGroupCount()==1)
System.out.println( matchResult.getGroup(0));
}

I don't know which regex library you are using but using the one from the JDK it would go along the lines of
String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String text = "[build]/directory/[something]/[build]/";
Pattern pat = Pattern.compile(linkPattern);
Matcher mat = pat.matcher(text);
while (mat.find()) {
System.out.println(mat.group());
}
Output:
[build]
[something]
[build]

Try:
String linkPattern = "(\\[[A-Za-z_0-9]+\\])*";
EDIT:
Second try:
String linkPattern = "\\[(\\w+)\\]+"
Third try, see http://rubular.com/r/eyAQ3Vg68N

Related

How to split string based on length and space using Java

I'm having a string as following in Java. The length of the string is not known and as an example it will be something like below.
String str = "I love programming. I'm currently working with Java and C++."
For some requirement I want to get first 15 characters. Then 30, 45, 70 next characters. Once the string was split if the name was not meaningful then it should be split from nearest space. For the above example output is as following.
String strSpli1 = "I love "; //Since 'programming' is splitting it was sent to next split
String strSpli2 = "programming. I'm currently ";//Since 'working' is splitting it was sent to next split
String strSpli3 = "working with Java and C++.";
Please help me to achieve this.
Updated answer for anybody having this kind of requirement.
String str = "I love programming. I'm currently working with Java and C++.";
String strSpli1 = "";
String strSpli2 = "";
String strSpli3 = "";
try {
strSpli1 = str.substring(15);
int pos = str.lastIndexOf(" ", 16);
if (pos == -1) {
pos = 15;
}
strSpli1 = str.substring(0, pos);
str = str.substring(pos);
try {
strSpli2 = str.substring(45);
int pos1 = str.lastIndexOf(" ", 46);
if (pos1 == -1) {
pos1 = 45;
}
strSpli2 = str.substring(0, pos1);
str = str.substring(pos1);
try {
strSpli3 = str.substring(70);
int pos2 = str.lastIndexOf(" ", 71);
if (pos2 == -1) {
pos2 = 45;
}
strSpli3 = str.substring(0, pos2);
str = str.substring(pos2);
} catch (Exception ex) {
strSpli3 = str;
}
} catch (Exception ex) {
strSpli2 = str;
}
} catch (Exception ex) {
strSpli1 = str;
}
Thank you
use the 2 parameter version of lastIndexOf() to search for space backwards starting from a given position. Example for the first 15 characters:
int pos = str.lastIndexOf(" ", 16);
if (pos == -1) {
pos = 15;
}
String found = str.substring(0, pos);
str = str.substring(pos+1);
this is missing checks like ensuring the string starts with at least 15 characters, or that pos+1 is valid for given length
suggest having a look at java.text.BreakIterator
why you use so many try catch ? just try this.
public class MyClass {
public static void main(String args[]) {
String str = "I love programming. I'm currently working with Java and C++.";
String strSpli1 = "";
String strSpli2 = "";
String strSpli3 = "";
strSpli1 = str.substring(0, 7);
strSpli2 = str.substring(7, 33);
strSpli3 = str.substring(34, str.length());
System.out.println(strSpli1+"\n");
System.out.println(strSpli2+"\n");
System.out.println(strSpli3+"\n");
}
use substring(start index, end index).

Masking - Address with Stars (asteriks) - If length of Array is 1?

I have an array out of bounds for this case.
If I do:
String address = "100 Point St Apt B"
It should be masked too: 100 Po*** St Apt *
If I do:
String address = "100 Point St Apt 132"
It is masked too: 100 Po*** St Apt ***
Can somebody tell me what I am doing wrong here? Thank you!!
public String mask(String address) {
String[] splitAddress = address.split(" ");
StringBuilder stringBuilder = new StringBuilder();
String maskedAddress = "";
String streetNum = splitAddress[0];
stringBuilder.append(streetNum + " ");
for (int i = 1; i < splitAddress.length; i++) {
String splitFirstTwoCharacters = splitAddress[i].substring(0, 2);
String remainingCharactersOfAddress = splitAddress[i].substring(2);
String maskAddress = remainingCharactersOfAddress.replaceAll(".", "*");
maskedAddress = stringBuilder.append(splitFirstTwoCharacters).append(maskAddress + " ").toString().trim();
}
return maskedAddress;
}
When you do splitAddress[i].substring(0, 2) one of the splitAddress parts is B which does not have an endIndex of 2. Therefore it is out of bounds.
Issue is you are running substring without checking the length of the string.
Here is the fix without too many changes to your existing code:
for (int i = 1; i < splitAddress.length; i++) {
if (splitAddress[i].length() <= 2) {
stringBuilder.append(splitAddress[i] + " ");
continue;
}
String splitFirstTwoCharacters = splitAddress[i].substring(0, 2);
String remainingCharactersOfAddress = splitAddress[i].substring(2);
String maskAddress = remainingCharactersOfAddress.replaceAll(".", "*");
maskedAddress = stringBuilder.append(splitFirstTwoCharacters).append(maskAddress + " ").toString().trim();
}
return stringBuilder.toString().trim();

Parsing a file and replacing White spaces fond within double quotes using Java

I am reading a file and trying to modify it in the following order:
if line is empty trim()
if line ends with \ strip that char and add next line to it.
The complete line contains double quotes and there are white spaces between the quotes, replace the white space with ~.
For example: "This is text within double quotes"
change to : "This~is~text~within~double~quotes"
This code is working but buggy.
Here is the issue when it finds a line that ends with \ and others that done.
for example:
line 1 and \
line 2
line 3
so Instead of having
line 1 and line 2
line 3
I have this:
line 1 and line 2 line 3
Coded updated:
public List<String> OpenFile() throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
String line;
//StringBuilder concatenatedLine = new StringBuilder();
List<String> formattedStrings = new ArrayList<>();
//Pattern matcher = Pattern.compile("\"([^\"]+)\"");
while ((line = br.readLine()) != null) {
boolean addToPreviousLine;
if (line.isEmpty()) {
line.trim();
}
if (line.contains("\"")) {
Matcher matcher = Pattern.compile("\"([^\"]+)\"").matcher(line);
while (matcher.find()) {
String match = matcher.group();
line = line.replace(match, match.replaceAll("\\s+", "~"));
}
}
if (line.endsWith("\\")) {
addToPreviousLine = false;
line = line.substring(0, line.length() - 1);
formattedStrings.add(line);
} else {
addToPreviousLine = true;
}
if (addToPreviousLine) {
int previousLineIndex = formattedStrings.size() - 1;
if (previousLineIndex > -1) {
// Combine the previous line and current line
String previousLine = formattedStrings.remove(previousLineIndex);
line = previousLine + " " + line;
formattedStrings.add(line);
}
}
testScan(formattedStrings);
//concatenatedLine.setLength(0);
}
return formattedStrings;
}
Update
I'm giving you what you need, without trying to write all the code for you. You just need to figure out where to place these snippets.
If line is empty trim()
if (line.matches("\\s+")) {
line = "";
// I don't think you want to add an empty line to your return result. If you do, just omit the continue;
continue;
}
If line contains double quotes and white spaces in them, replace the white space with ~. For example: "This is text within double quotes" change to : "This~is~text~within~double~quotes"
Matcher matcher = Pattern.compile("\"([^\"]+)\"").matcher(line);
while (matcher.find()) {
String match = matcher.group();
line = line.replace(match, match.replaceAll("\\s+", "~"));
}
If line ends with \ strip that char and add the next line. You need to have flag to track when to do this.
if (line.endsWith("\\")) {
addToPreviousLine = true;
line = line.substring(0, line.length() - 1);
} else {
addToPreviousLine = false;
}
Now, to add the next line to the previous line you'll need something like (Figure out where to place this snippet):
if (addToPreviousLine) {
int previousLineIndex = formattedStrings.size() - 1;
if (previousLineIndex > -1) {
// Combine the previous line and current line
String previousLine = formattedStrings.remove(previousLineIndex);
line = previousLine + " " + line;
}
}
You still do not need the StringBuffer or StringBuilder. Just modify the current line and add the current line to your formattedStrings List.
I'm not very good with regex, so here's a programmatic method to do it:
String string = "He said, \"Hello Mr Nice Guy\"";
// split it along the quotes
String splitString[] = string.split("\"");
// loop through, each odd indexted item is inside quotations
for(int i = 0; i < splitString.length; i++) {
if(i % 2 > 0) {
splitString[i] = splitString[i].replaceAll(" ", "~");
}
}
String finalString = "";
// re-build the string w/ quotes added back in
for(int i = 0; i < splitString.length; i++) {
if(i % 2 > 0) {
finalString += "\"" + splitString[i] + "\"";
} else {
finalString += splitString[i];
}
}
System.out.println(finalString);
Output: He said, "Hello~Mr~Nice~Guy"
Step 3:
String text;
text = text.replaceAll("\\s", "~");
If you want to replace spaces occur within double quotes with ~s,
if (line.contains("\"")) {
String line = "\"This is a line with spaces\"";
String result = "";
Pattern p = Pattern.compile("\"([^\"]*)\"");
Matcher m = p.matcher(line);
while (m.find()) {
result = m.group(1).replace(" ", "~");
}
}
instead of
if (line.contains("\"")) {
StringBuffer sb = new StringBuffer();
Matcher matcher = Pattern.compile("\"([^\"]+)\"").matcher(line);
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group().replaceAll("\\s+", ""));
}
I would do this
if (line.matches(("\"([^\"]+)\"")) {
line= line.replaceAll("\\s+", ""));
}
How can I add this to what I have above ?
concatenatedLine.append(line);
String fullLine = concatenatedLine.toString();
if (fullLine.contains("\"")) {
StringBuffer sb = new StringBuffer();
Matcher matcher = Pattern.compile("\"([^\"]+)\"").matcher(fullLine);
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group().replaceAll("\\s+", ""));
formattedStrings.add(sb.toString());
}else
formattedStrings.add(fullLine);

How to add characters to a string in specific indexes?

I have a string formed with 6 letters eg: "abcdef".
I need to add "." every two characters so it would be like this: "ab.cd.ef".
I'm working in java, I tried this:
private String FormatAddress(String sourceAddress) {
char[] sourceAddressFormatted = new char[8];
sourceAddress.getChars(0, 1, sourceAddressFormatted, 0);
sourceAddress += ".";
sourceAddress.getChars(2, 3, sourceAddressFormatted, 3);
sourceAddress += ".";
sourceAddress.getChars(4, 5, sourceAddressFormatted, 6);
String s = new String(sourceAddressFormatted);
return s;
}
But i received strange values such as [C#2723b6.
Thanks in advance:)
Try regexp:
Input:
abcdef
Code:
System.out.println("abcdef".replaceAll(".{2}(?!$)", "$0."));
Output:
ab.cd.ef
You should fix it as
String sourceAddress = "abcdef";
String s = sourceAddress.substring(0, 2);
s += ".";
s += sourceAddress.substring(2, 4);
s += ".";
s += sourceAddress.substring(4, 6);
System.out.println(s);
You also can do the same with regex, it's a one line solution
String s = sourceAddress.replaceAll("(\\w\\w)(?=\\w\\w)", "$1.");
System.out.println(s);
private String formatAddress(String sourceAddress) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sourceAddress.length(); i+=2) {
sb.append(sourceAddress.substring(i, i+2));
if (i != sourceAddress.length()-1) {
sb.append('.');
}
}
return sb.toString();
}
Try this:
String result="";
String str ="abcdef";
for(int i =2; i<str.length(); i=i+2){
result = result + str.substring(i-2 , i) + ".";
}
result = result + str.substring(str.length()-2);

Java special characters RegEx

I want to achieve following using Regular expression in Java
String[] paramsToReplace = {"email", "address", "phone"};
//input URL string
String ip = "http://www.google.com?name=bob&email=okATtk.com&address=NYC&phone=007";
//output URL string
String op = "http://www.google.com?name=bob&email=&address=&phone=";
The URL can contain special characters like %
Try this expression: (email=)[^&]+ (replace email with your array elements) and replace with the group: input.replaceAll("("+ paramsToReplace[i] + "=)[^&]+", "$1");
String input = "http://www.google.com?name=bob&email=okATtk.com&address=NYC&phone=007";
String output = input;
for( String param : paramsToReplace ) {
output = output.replaceAll("("+ param + "=)[^&]+", "$1");
}
For the example above. you can use split
String[] temp = ip.split("?name=")[1].split("&")[0];
op = temp[0] + "?name=" + temp[1].split("&")[0] +"&email=&address=&phone=";
Something like this?
private final static String REPLACE_REGEX = "=.+\\&";
ip=ip+"&";
for(String param : paramsToReplace) {
ip = ip.replaceAll(param+REPLACE_REGEX, Matcher.quoteReplacement(param+"=&"));
}
P.S. This is only a concept, i didn't compile this code.
You don't need regular expressions to achieve that:
String op = ip;
for (String param : paramsToReplace) {
int start = op.indexOf("?" + param);
if (start < 0)
start = op.indexOf("&" + param);
if (start < 0)
continue;
int end = op.indexOf("&", start + 1);
if (end < 0)
end = op.length();
op = op.substring(0, start + param.length() + 2) + op.substring(end);
}

Categories

Resources