java正则表达式indexof,Java String.indexOf()可以将正则表达式作为参数处理吗?

I want to capture the index of a particular regular expression in a Java String. That String may be enclosed with single quote or double quotes (sometimes no quotes). How can I capture that index using Java?

eg:

capture String --> class = ('|"|)word('|"|)

解决方案

No.

WorkAround :

Its not standard practice but you can get result using this.

Update:

CharSequence inputStr = "abcabcab283c";

String patternStr = "[1-9]{3}";

Pattern pattern = Pattern.compile(patternStr);

Matcher matcher = pattern.matcher(inputStr);

if(matcher.find()){

System.out.println(matcher.start());//this will give you index

}

OR

Regex r = new Regex("YOURREGEX");

// search for a match within a string

r.search("YOUR STRING YOUR STRING");

if(r.didMatch()){

// Prints "true" -- r.didMatch() is a boolean function

// that tells us whether the last search was successful

// in finding a pattern.

// r.left() returns left String , string before the matched pattern

int index = r.left().length();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java的`indexOf`方法并不支持直接使用正则表达式进行匹配。`indexOf`方法是用来查找指定字符或字符串在目标字符串中的位置,它接受一个参数,即要查找的字符或字符串,返回值是目标字符串中第一次出现该字符或字符串的索引。如果没有找到,则返回-1。 如果你想在Java中使用正则表达式进行匹配,可以使用`Pattern`和`Matcher`类来实现。下面是一个简单的示例: ```java import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main(String[] args) { String text = "Hello, world!"; String pattern = "wo\\w+"; // 匹配以"wo"开头,后面跟一个或多个字母字符的字符串 Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(text); if (m.find()) { int startIndex = m.start(); int endIndex = m.end(); String match = text.substring(startIndex, endIndex); System.out.println("匹配到的字符串:" + match); System.out.println("起始索引:" + startIndex); System.out.println("结束索引:" + endIndex); } else { System.out.println("未找到匹配的字符串"); } } } ``` 输出结果: ``` 匹配到的字符串:world 起始索引:7 结束索引:12 ``` 在上面的示例中,我们使用了`Pattern.compile`方法编译了一个正则表达式,并使用`Matcher`类的`find`方法来查找匹配项。如果找到了匹配项,我们可以通过`start`和`end`方法获取匹配项在目标字符串中的起始索引和结束索引,然后使用`substring`方法获取匹配到的字符串。 希望能对你有所帮助!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值