Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🚀 Add regex replace #4323

Closed
Closed
Changes from 14 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
b767f4a
🚀 Add regex replace
AyhamAl-Ali Sep 7, 2021
7ae2743
Merge branch 'master' into ench/regex-replace
AyhamAl-Ali Jun 24, 2022
fbf3112
RC
AyhamAl-Ali Jun 24, 2022
b932fce
Merge branch 'master' into ench/regex-replace
TheLimeGlass Jul 13, 2022
58ef654
Update src/main/java/ch/njol/skript/effects/EffReplace.java
AyhamAl-Ali Aug 6, 2022
94be128
Update src/main/java/ch/njol/skript/effects/EffReplace.java
AyhamAl-Ali Aug 6, 2022
9f6b2df
Update src/main/java/ch/njol/skript/effects/EffReplace.java
AyhamAl-Ali Aug 6, 2022
785ef94
Auto stash before merge of "ench/regex-replace" and "AyhamAl-Ali/ench…
AyhamAl-Ali Aug 6, 2022
5820bd9
Add [the]
AyhamAl-Ali Aug 6, 2022
fbeb4ba
Fix build
AyhamAl-Ali Aug 6, 2022
e4cf911
Merge branch 'master' into ench/regex-replace
AyhamAl-Ali Aug 26, 2022
e603f6c
Update src/main/java/ch/njol/skript/effects/EffReplace.java
AyhamAl-Ali Jan 1, 2023
6f6241c
Better variable naming
AyhamAl-Ali Jan 2, 2023
26f5014
p -> pattern
AyhamAl-Ali Jan 2, 2023
05f6068
Merge branch 'master' into ench/regex-replace
AyhamAl-Ali Aug 21, 2023
f55124d
Fix merge to master conflicts
AyhamAl-Ali Aug 22, 2023
bf321ab
Fix tests
AyhamAl-Ali Aug 22, 2023
c545523
Merge branch 'master' into ench/regex-replace
AyhamAl-Ali Sep 13, 2023
3a501f5
Merge branch 'dev/feature' into ench/regex-replace
AyhamAl-Ali Oct 5, 2023
d78fe22
Address reviews
AyhamAl-Ali Apr 5, 2024
2750f1f
Merge remote-tracking branch 'AyhamAl-Ali/ench/regex-replace' into en…
AyhamAl-Ali Apr 5, 2024
255696e
Fix build
AyhamAl-Ali Apr 5, 2024
73da21b
Merge branch 'dev/feature' into ench/regex-replace
Moderocky Apr 10, 2024
026655e
Update src/main/java/ch/njol/skript/effects/EffReplace.java
sovdeeth Jun 28, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 78 additions & 51 deletions src/main/java/ch/njol/skript/effects/EffReplace.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,102 +37,129 @@
import org.bukkit.inventory.ItemStack;
import org.eclipse.jdt.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Name("Replace")
@Description("Replaces all occurrences of a given text with another text. Please note that you can only change variables and a few expressions, e.g. a <a href='../expressions.html#ExprMessage'>message</a> or a line of a sign.")
@Examples({"replace \"<item>\" in {textvar} with \"%item%\"",
"replace every \"&\" with \"§\" in line 1",
"# The following acts as a simple chat censor, but it will e.g. censor mass, hassle, assassin, etc. as well:",
"on chat:",
" replace all \"kys\", \"idiot\" and \"noob\" with \"****\" in the message",
" ",
"replace all stone and dirt in player's inventory and player's top inventory with diamond"})
@Since("2.0, 2.2-dev24 (replace in multiple strings and replace items in inventory), 2.5 (replace first, case sensitivity)")
@Description("Replaces all occurrences of a given text/regex with another text. Please note that you can only change " +
"variables and a few expressions, e.g. a <a href='/expressions.html#ExprMessage'>message</a> or a line of a sign.")
@Examples({
"replace \"<item>\" in {_msg} with \"[%name of player's tool%]\"",
"replace every \"&\" with \"§\" in line 1 of targeted block",
"",
"# Very simple chat censor",
"on chat:",
"\treplace all \"kys\", \"idiot\" and \"noob\" with \"****\" in the message",
"\treplace using regex \"\\b(kys|idiot|noob)\\b\" with \"****\" in the message # Regex version for better results",
"",
"replace all stone and dirt in player's inventory and player's top inventory with diamond"
})
@Since("2.0, 2.2-dev24 (multiple strings, items in inventory), 2.5 (replace first, case sensitivity), INSERT VERSION (regex)")
public class EffReplace extends Effect {

static {
Skript.registerEffect(EffReplace.class,
AyhamAl-Ali marked this conversation as resolved.
Show resolved Hide resolved
"replace (all|every|) %strings% in %strings% with %string% [(1¦with case sensitivity)]",
"replace (all|every|) %strings% with %string% in %strings% [(1¦with case sensitivity)]",
"replace first %strings% in %strings% with %string% [(1¦with case sensitivity)]",
"replace first %strings% with %string% in %string% [(1¦with case sensitivity)]",
"replace (all|every|) %itemtypes% in %inventories% with %itemtype%",
"replace (all|every|) %itemtypes% with %itemtype% in %inventories%");
"replace [all:(all|every)|first:[the] first] %strings% in %strings% with %string% [case:with case sensitivity]",
"replace [all:(all|every)|first:[the] first] %strings% with %string% in %strings% [case:with case sensitivity]",
"regex:(replace [using] regex|regex replace) %strings% in %strings% with %string%",
"regex:(replace [using] regex|regex replace) %strings% with %string% in %strings%",
Comment on lines +68 to +69
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we could also just check the matchedPattern here rather than a regex parse tag

"replace [all|every] %itemtypes% in %inventories% with %itemtype%",
"replace [all|every] %itemtypes% with %itemtype% in %inventories%");
}
@SuppressWarnings("null")

@SuppressWarnings("NotNullFieldNotInitialized")
private Expression<?> haystack, needles, replacement;
private boolean replaceString = true;
private boolean replaceFirst = false;
private boolean replaceString;
private boolean replaceRegex;
private boolean replaceItems;
private boolean replaceFirst;
private boolean caseSensitive = false;

@SuppressWarnings({"null"})
@Override
@SuppressWarnings("null")
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
haystack = exprs[1 + matchedPattern % 2];
replaceString = matchedPattern < 4;
replaceFirst = matchedPattern > 1 && matchedPattern < 4;
replaceFirst = parseResult.hasTag("first");
replaceRegex = parseResult.hasTag("regex");
replaceItems = matchedPattern == 4 || matchedPattern == 5;
AyhamAl-Ali marked this conversation as resolved.
Show resolved Hide resolved
if (replaceString && !ChangerUtils.acceptsChange(haystack, ChangeMode.SET, String.class)) {
AyhamAl-Ali marked this conversation as resolved.
Show resolved Hide resolved
Skript.error(haystack + " cannot be changed and can thus not have parts replaced.");
Skript.error(haystack + " cannot be changed and can thus not have parts replaced");
return false;
}
if (SkriptConfig.caseSensitive.value() || parseResult.mark == 1) {
if (SkriptConfig.caseSensitive.value() || parseResult.hasTag("case")) {
caseSensitive = true;
}
needles = exprs[0];
replacement = exprs[2 - matchedPattern % 2];
return true;
}

@SuppressWarnings("null")

@Override
protected void execute(Event e) {
Object[] haystack = this.haystack.getAll(e);
Object[] needles = this.needles.getAll(e);
Object replacement = this.replacement.getSingle(e);
@SuppressWarnings("null")
protected void execute(Event event) {
Object[] haystack = this.haystack.getAll(event);
Object[] needles = this.needles.getAll(event);
Object replacement = this.replacement.getSingle(event);
if (replacement == null || haystack == null || haystack.length == 0 || needles == null || needles.length == 0)
return;
if (replaceString) {
if (replaceFirst) {
for (int x = 0; x < haystack.length; x++)
for (Object n : needles) {
assert n != null;
haystack[x] = StringUtils.replaceFirst((String)haystack[x], (String)n, Matcher.quoteReplacement((String)replacement), caseSensitive);
for (int i = 0; i < haystack.length; i++) {
for (Object needle : needles) {
assert needle != null;
haystack[i] = StringUtils.replaceFirst((String) haystack[i], (String) needle, Matcher.quoteReplacement((String) replacement), caseSensitive);
}
}
} else if (replaceRegex) {
List<Pattern> patterns = new ArrayList<>(needles.length);
for (Object needle : needles) {
assert needle != null;
try {
patterns.add(Pattern.compile((String) needle));
} catch (Exception ignored) {}
}
for (int i = 0; i < haystack.length; i++) {
for (Pattern pattern : patterns) {
assert pattern != null;
haystack[i] = pattern.matcher((String) haystack[i]).replaceAll((String) replacement);
}
}
} else {
for (int x = 0; x < haystack.length; x++)
for (Object n : needles) {
assert n != null;
haystack[x] = StringUtils.replace((String) haystack[x], (String) n, (String) replacement, caseSensitive);
for (int i = 0; i < haystack.length; i++) {
for (Object needle : needles) {
assert needle != null;
haystack[i] = StringUtils.replace((String) haystack[i], (String) needle, (String) replacement, caseSensitive);
}
}
}
this.haystack.change(e, haystack, ChangeMode.SET);
} else {
for (Inventory inv : (Inventory[]) haystack)
for (ItemType needle : (ItemType[]) needles)
for (Map.Entry<Integer, ? extends ItemStack> entry : inv.all(needle.getMaterial()).entrySet()) {
this.haystack.change(event, haystack, ChangeMode.SET);
} else if (replaceItems) {
for (Inventory inventory : (Inventory[]) haystack) {
for (ItemType needle : (ItemType[]) needles) {
for (Map.Entry<Integer, ? extends ItemStack> entry : inventory.all(needle.getMaterial()).entrySet()) {
int slot = entry.getKey();
ItemStack itemStack = entry.getValue();

if (new ItemType(itemStack).isSimilar(needle)) {
ItemStack newItemStack = ((ItemType) replacement).getRandom();
newItemStack.setAmount(itemStack.getAmount());

inv.setItem(slot, newItemStack);
inventory.setItem(slot, newItemStack);
}
}
}
}
}
}

@Override
public String toString(@Nullable Event e, boolean debug) {
if (replaceFirst)
return "replace first " + needles.toString(e, debug) + " in " + haystack.toString(e, debug) + " with " + replacement.toString(e, debug)
+ "(case sensitive: " + caseSensitive + ")";
return "replace " + needles.toString(e, debug) + " in " + haystack.toString(e, debug) + " with " + replacement.toString(e, debug)
+ "(case sensitive: " + caseSensitive + ")";
public String toString(@Nullable Event event, boolean debug) {
return "replace " + (replaceFirst ? "first " : (replaceRegex ? "regex " : "")) + needles.toString(event, debug)
+ " in " + haystack.toString(event, debug) + " with " + replacement.toString(event, debug)
+ (caseSensitive ? " with case sensitivity" : "");
}

}