如何在Java中使用正则表达式来操作字符串


String s = "My cake should have ( sixteen | sixten | six teen ) candles, I love and ( should be | would be ) puff them."

最终修改字符串

My cake should have <div><p id="1">sixteen</p><p  id="2">sixten</p><p  id="3">six teen</p></div>  candles, I love and <div><p  id="1">should be</p><p  id="2"> would be</p> puff them

我试过使用这个:

Pattern pattern = Pattern.compile("\|\s*(.*?)(?=\s*\|)");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
System.out.println(matcher.group(1));
}

使用

import java.util.regex.*;
class Program
{
public static void main (String[] args) throws java.lang.Exception
{
String s = "My cake should have ( sixteen | sixten | six teen ) candles, I love and ( should be | would be ) puff them.";
Pattern pattern = Pattern.compile("\(([^()|]*\|[^()]*)\)");
Matcher matcher = pattern.matcher(s);
StringBuffer changed = new StringBuffer();
while (matcher.find()){
String temp = "<div>";
String[] items = matcher.group(1).trim().split("\s*\|\s*");
for (int i = 1; i<=items.length; i++) {
temp += "<p id="" + i + "">" + items[i-1] + "</p>";
}
matcher.appendReplacement(changed, temp+"</div>");
}
matcher.appendTail(changed);
System.out.println(changed.toString());
}
}

参见Java证明。

结果:My cake should have <div><p id="1">sixteen</p><p id="2">sixten</p><p id="3">six teen</p></div> candles, I love and <div><p id="1">should be</p><p id="2">would be</p></div> puff them.

正则表达式使用

(([^()|]*|[^()]*))

--------------------------------------------------------------------------------
(                       '('
--------------------------------------------------------------------------------
(                        group and capture to 1:
--------------------------------------------------------------------------------
[^()|]*                  any character except: '(', ')', '|' (0
or more times (matching the most amount
possible))
--------------------------------------------------------------------------------
|                       '|'
--------------------------------------------------------------------------------
[^()]*                   any character except: '(', ')' (0 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
)                        end of 1
--------------------------------------------------------------------------------
)                       ')'

:将父元素与管道匹配,将没有父元素的内容与管道分开,修剪,用循环组合成一个字符串。StringBuffermatcher.appendReplacement在替换过程中使用字符串操作。

相关内容

  • 没有找到相关文章

最新更新