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
Show file tree
Hide file tree
Changes from 4 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
92 changes: 56 additions & 36 deletions src/main/java/ch/njol/skript/effects/EffReplace.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,98 +41,118 @@
import java.util.regex.Matcher;

@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)")
AyhamAl-Ali marked this conversation as resolved.
Show resolved Hide resolved
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% [(with case sensitivity)]",
"replace (all|every|) %strings% with %string% in %strings% [(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:(all|every)|:first|) %strings% in %strings% with %string% [(case:with case sensitivity)]",
"replace (all:(all|every)|:first|) %strings% with %string% in %strings% [(case:with case sensitivity)]",
AyhamAl-Ali marked this conversation as resolved.
Show resolved Hide resolved
"(regex:(replace [using] regex|regex replace)) %strings% in %strings% with %string%",
"(regex:(replace [using] regex|regex replace)) %strings% with %string% in %strings%",
AyhamAl-Ali marked this conversation as resolved.
Show resolved Hide resolved
"replace (all|every|) %itemtypes% in %inventories% with %itemtype%",
"replace (all|every|) %itemtypes% with %itemtype% in %inventories%");
}

@SuppressWarnings("null")
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;
replaceString = matchedPattern < 2;
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.");
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
@SuppressWarnings("null")
protected void execute(Event e) {
AyhamAl-Ali marked this conversation as resolved.
Show resolved Hide resolved
Object[] haystack = this.haystack.getAll(e);
Object[] needles = this.needles.getAll(e);
Object replacement = this.replacement.getSingle(e);
if (replacement == null || haystack == null || haystack.length == 0 || needles == null || needles.length == 0)
return;
if (replaceString) {
if (replaceString || replaceRegex) {
if (replaceFirst) {
for (int x = 0; x < haystack.length; x++)
for (int x = 0; x < haystack.length; x++) {
AyhamAl-Ali marked this conversation as resolved.
Show resolved Hide resolved
for (Object n : needles) {
AyhamAl-Ali marked this conversation as resolved.
Show resolved Hide resolved
assert n != null;
haystack[x] = StringUtils.replaceFirst((String)haystack[x], (String)n, Matcher.quoteReplacement((String)replacement), caseSensitive);
haystack[x] = StringUtils.replaceFirst((String) haystack[x], (String) n, Matcher.quoteReplacement((String) replacement), caseSensitive);
}
}
} else if (replaceRegex) {
for (int x = 0; x < haystack.length; x++) {
for (Object n : needles) {
assert n != null;
try {
haystack[x] = ((String) haystack[x]).replaceAll((String) n, (String) replacement);
} catch (Exception ignored) {}
AyhamAl-Ali marked this conversation as resolved.
Show resolved Hide resolved
}
}
} else {
for (int x = 0; x < haystack.length; x++)
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);
}
}
}
this.haystack.change(e, haystack, ChangeMode.SET);
} else {
for (Inventory inv : (Inventory[]) haystack)
for (ItemType needle : (ItemType[]) needles)
} else if (replaceItems) {
for (Inventory inv : (Inventory[]) haystack) {
for (ItemType needle : (ItemType[]) needles) {
for (Map.Entry<Integer, ? extends ItemStack> entry : inv.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);
}
}
}
}
}
}

@Override
public String toString(@Nullable Event e, boolean debug) {
AyhamAl-Ali marked this conversation as resolved.
Show resolved Hide resolved
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 + ")";
return "replace " + (replaceFirst ? "first " : (replaceRegex ? "regex " : "")) + needles.toString(e, debug)
+ " in " + haystack.toString(e, debug) + " with " + replacement.toString(e, debug)
+ "(case sensitive: " + caseSensitive + ")";
AyhamAl-Ali marked this conversation as resolved.
Show resolved Hide resolved
}

}
2 changes: 1 addition & 1 deletion src/main/java/ch/njol/skript/lang/Expression.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public interface Expression<T> extends SyntaxElement, Debuggable {
/**
* Get the single value of this expression.
* <p>
* This method may only return null if it always returns null for the given event, i.e. it is equivalent to getting a random element out of {@link #getAll(Event)} or null iff
* This method may only return null if it always returns null for the given event, i.e. it is equivalent to getting a random element out of {@link #getAll(Event)} or null if
AyhamAl-Ali marked this conversation as resolved.
Show resolved Hide resolved
* that array is empty.
* <p>
* Do not use this in conditions, use {@link #check(Event, Checker, boolean)} instead.
Expand Down